我正在嘗試列印forecast.dart,但我正在列印“WeatherData 實體”。我添加了@override String toString()但沒有更改..我不太確定為什么沒有列印出forecast.dart..請幫忙!
在weatherData.dart
class WeatherData {
String? placeName;
num? temperature;
num? feels_like;
num? pressure;
num? humidity;
num? wind_speed;
WeatherData({
this.placeName,
this.temperature,
this.feels_like,
this.pressure,
this.humidity,
this.wind_speed,
});
@override
String toString();
WeatherData.fromJson(Map<String, dynamic> json) {
placeName = json['city']['name'];
temperature = json['list'][0]['main']['temp'];
feels_like = json['list'][0]['main']['temp'];
pressure = json['list'][0]['main']['temp'];
humidity = json['list'][0]['main']['temp'];
wind_speed = json['list'][0]['main']['temp'];
}
}
在預測.dart
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 weatherData = [];
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']);
weatherData.add(w);
print(weatherData.toList());
});
return ForecastData(list: weatherData);
}
}
輸出
I/flutter (21227): [Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of
uj5u.com熱心網友回復:
@override
String toString();
您需要實際添加一個實作。return您想在列印時看到的字串。
uj5u.com熱心網友回復:
您需要實施toString. 例如,你可以這樣做:
@override
String toString() => 'Weather for ${placeName ?? 'unknown'}';
或者,您可以使用https://pub.dev/packages/freezed。它會自動為您生成有用的函式(例如fromJson、toJson、toString)。這樣你會節省很多時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401647.html
上一篇:如何修復類名的錯誤實體?
