【发布时间】:2022-01-02 00:43:38
【问题描述】:
我不知道我是否正确地迭代了每个项目。屏幕上什么都没有呈现,我有以下错误说 '迭代期间的并发修改:'_GrowableList'的实例(长度:41)我不确定如何修复此错误并在屏幕上呈现每个项目。有什么想法吗?
import 'package:forecast/models/weather_data.dart';
class ForecastData {
final List list;
ForecastData({required this.list});
factory ForecastData.fromJson(Map<String, dynamic> json) {
var list = json['list']?.map((e) => e)?.toList(growable: true) ?? [];
list.forEach((e) {
WeatherData w = WeatherData(
placeName: json['city']['name'],
temperature: e['main']['temp'],
feels_like: e['main']['temp'],
pressure: e['main']['temp'],
humidity: e['main']['temp'],
wind_speed: e['main']['temp']);
list.add(w);
print(list);
});
return ForecastData(
list: list,
);
}
}
输出
Restarted application in 4,038ms.
I/flutter (16409): [{dt: 1641081600, main: {temp: 12.94, feels_like: 12.64, temp_min: 12.8, temp_max: 12.94, pressure: 1014, sea_level: 1014, grnd_level: 1010, humidity: 90, temp_kf: 0.14}, weather: [{id: 803, main: Clouds, description: broken clouds, icon: 04n}], clouds: {all: 75}, wind: {speed: 5.32, deg: 211, gust: 12.51}, visibility: 10000, pop: 0.23, sys: {pod: n}, dt_txt: 2022-01-02 00:00:00}, {dt: 1641092400, main: {temp: 12.86, feels_like: 12.53, temp_min: 12.69, temp_max: 12.86, pressure: 1013, sea_level: 1013, grnd_level: 1008, humidity: 89, temp_kf: 0.17}, weather: [{id: 500, main: Rain, description: light rain, icon: 10n}], clouds: {all: 83}, wind: {speed: 4.85, deg: 224, gust: 12.6}, visibility: 10000, pop: 0.62, rain: {3h: 0.94}, sys: {pod: n}, dt_txt: 2022-01-02 03:00:00}, {dt: 1641103200, main: {temp: 12.71, feels_like: 12.18, temp_min: 12.59, temp_max: 12.71, pressure: 1011, sea_level: 1011, grnd_level: 1007, humidity: 82, temp_kf: 0.12}, weather: [{id: 500, main: Rain, description: light rain, icon: 10n}], cl
E/flutter (16409): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Concurrent modification during iteration: Instance(length:41) of '_GrowableList'.
E/flutter (16409): #0 List.forEach (dart:core-patch/growable_array.dart:411:36)
E/flutter (16409): #1 new ForecastData.fromJson (package:forecast/models/forecast_data.dart:10:10)
E/flutter (16409): #2 _MyAppState.loadForecast.<anonymous closure> (package:forecast/main.dart:121:37)
E/flutter (16409): #3 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter (16409): #4 _MyAppState.loadForecast (package:forecast/main.dart:120:14)
E/flutter (16409): <asynchronous suspension>
【问题讨论】: