【问题标题】:Flutter JSON serialization errorFlutter JSON 序列化错误
【发布时间】:2018-11-26 03:00:45
【问题描述】:

我想从传入的 API 请求将 JSON 对象序列化为我的本机类对象。但是,当映射发生并且FutureBuilder 尝试返回数据时,它会生成如下运行时错误:

type _CastError 不是 bool 的子类型

同时使用列表返回数据和

type _TypeError 不是 bool 的子类型

从错误中我假设它无法从流中转换数据。我在学习 Flutter 时没有太多想法。

这是我提出请求的未来:

Future getWeatherInfo(String city) async {
Uri uri = new Uri.https("api.apixu.com", "/v1/current.json",
  {"key": <key>, "q": city});
print(uri);
final response = await http.get(uri);
final responseJSON = jsonDecode(response.body);
print(responseJSON);
return BaseClass.getData(responseJSON);

原生类:

class BaseClass {
// final WeatherInformation weatherInformation;
final Weather weather;
BaseClass({this.weather});
factory BaseClass.getData(Map jsonData) {
return new BaseClass(
  // weatherInformation: (jsonData["location"])
  //     .map((i) => WeatherInformation.weatherValues(i)),
  weather: (jsonData["current"])
      .map((i) => Weather.weatherData(i)),
);
}}


class WeatherInformation {
final String cityName;
final String cityRegion;
final String country;
final double lat;
final double long;
final String time;

WeatherInformation({
this.cityName,
this.cityRegion,
this.country,
this.time,
this.lat,
this.long,
});

factory WeatherInformation.weatherValues(Map data) {
  return new WeatherInformation(
  cityRegion: data['cityRegion'],
  cityName: data['name'],
  country: data['country'],
  lat: data['lat'],
  long: data['long'],
  time: data['localtime'],
);
}
}

class Weather {
final Condition condition;

final double windmph;
final double windkph;
final double winddegree;
final int cloud;
final double pressuremb;
final double pressurein;
final double precipmm;
final double precipin;
final int humidity;
final double centrigade;
final double faranheit;
final double tempc;
final double tempf;

Weather({
this.centrigade,
this.cloud,
this.faranheit,
this.humidity,
this.pressuremb,
this.tempc,
this.precipmm,
this.precipin,
this.pressurein,
this.tempf,
this.winddegree,
this.windkph,
this.windmph,
this.condition,
});

factory Weather.weatherData(Map data) {
return new Weather(
  tempc: data['temp_c'],
  tempf: data['temp_f'],
  windmph: data['wind_mph'],
  windkph: data['wind_kph'],
  winddegree: data['wind_degree'],
  pressuremb: data['pressure_mb'],
  pressurein: data['pressure_in'],
  precipmm: data['precip_mm'],
  precipin: data['precip_in'],
  humidity: data['humidity'],
  cloud: data['cloud'],
  centrigade: data['feelslike_c'],
  faranheit: data['feelslike_f'],
  // condition:
  //     (data['condition'] as List).map((i) => Condition.toJSON(i)).toList(),
);
}
}

class Condition {
String text;
String icon;

Condition({
Key key,
this.text,
this.icon,
});

Condition.toJSON(Map data)
  : icon = data['icon'],
    text = data['text'];
}

列表视图:

** if (snapshot.hasError)** { //(previously was snapshot.error)
return new Center(
child: new Chip(
label: new Text('Error! Please try again',style: new TextStyle(color: 
Colors.white),)));
} else if (snapshot.hasData) {
return new ListView(
shrinkWrap:false,
children: <Widget>[
new ListTile(
leading: new Text("Calvin"),
                      title: new 
Text(snapshot.data.weather[0].tempc.toString(),
style: new TextStyle(color: Colors.white)),),
new ListTile(
leading: new Text('Pressure'),
title: new Text(
snapshot.data.weather[0].pressurein.toString(),
style: new TextStyle(color: Colors.white)),
 ),
new ListTile(
title: new Text(snapshot.data.weather[0].cloud.toString()),
leading: new Icon(Icons.cloud)),
 ],
 );
 }

【问题讨论】:

  • 您在代码中的哪里得到错误?你在某处有if 声明吗?
  • 是的,我正在检查快照是否有错误,同时构建ListView。
  • 你能把这段代码添加到你的问题中吗?
  • 我使用了返回 Object 的错误属性:[
  • 我希望他们只记录错误的字段,而不是让我们陷入猜谜游戏。

标签: json dart flutter


【解决方案1】:

未来没有类型。因此,AsyncSnapshot 可能无法正常工作。

在上面的第一个列表中使用Future&lt;BaseClass&gt;,

然后,在FutureBuilder 中添加如下:

new FutureBuilder<BaseClass>(
  future: getWeatherInfo(...),
  builder: (BuildContext context, AsyncSnapshot<BaseClass> snapshot) {
....

【讨论】:

  • 事实上,我已经将未来的类型设置为 BaseClass 但我无法访问列表和类属性,所以默认情况下我将其保留为动态
  • 我遇到了一个异常,它说 _InternalLinkedHashmap 不是 List 类型的子类型
  • 那么你应该尝试解决这个错误。某处你正在传递一个地图,而它正在期待一个列表。尝试找到发生这种情况的行。工厂里的jsonData["current"]是List还是Map?如果你在上面调用.map()方法,它应该是一个列表。
猜你喜欢
  • 1970-01-01
  • 2015-02-07
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多