Flutter:当我尝试访问 JSON 数据元素时出现 TypeError [英] Flutter: TypeError when I try to access elements of JSON data
问题描述
我正在尝试在动态列表视图上显示 JSON 数据的各个元素.但是,我不断收到'int' 类型不是'String' 类型的子类型"错误,我不知道为什么.
I am trying to display individual elements of a JSON data on a dynamic listview. However, I keep getting "type 'int' is not a subtype of type 'String'" error and I have no idea why.
如果我在 buildFlightsColumn 函数中的 Row 下的小部件中只包含 left() 函数,则代码有效.但是一旦我包含了 middle() 和 right() 函数,我就会收到错误消息.
The code works if I include just the left() function in the widget located under the Row in the buildFlightsColumn function. But once I include the middle() and right() functions, I get the error.
Widget buildListView() {
print(data);
return ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index) {
return buildFlightsColumn(data[index]);
}
);
}
Widget buildFlightsColumn(dynamic item) => Container(
height: 150.0,
decoration: BoxDecoration(
),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
left(item['PlaceId']),
middle(item['IataCode']),
right()
],
),
);
Container left(dynamic item) {
return new Container (
child: Text(
item,
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 25.0,
color: Colors.red,
)
),
);
}
Container middle(dynamic item) {
return new Container(
child: Text(
item,
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 25.0,
color: Colors.red,
)
),
);
}
Container right() {
return new Container(
child: RaisedButton(
onPressed: () {
},
child: Text('Book Flights'),
)
);
}
传入buildFlightsColumn函数的数据是API请求返回的JSON数据:
The data passed into the buildFlightsColumn function is JSON data returned by the API request:
[{PlaceId: 65368, IataCode: LAX, Name: Los Angeles International, Type: Station, SkyscannerCode: LAX, CityName: Los Angeles, CityId: LAXA, CountryName: United States}, {PlaceId: 81727, IataCode: SFO, Name: San Francisco International, Type: Station, SkyscannerCode: SFO, CityName: San Francisco, CityId: SFOA, CountryName: United States}]
推荐答案
我认为问题在于 PlaceId 是 int 类型,但您尝试将其用作 String.
I think the problem is that PlaceId is of type int but you try to use it as a String.
像这样改变你的代码:
Container left(dynamic item) {
return new Container (
child: Text(
item.toString(), //change the type here
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 25.0,
color: Colors.red,
)
),
);
}
或者像这样:
Widget buildFlightsColumn(dynamic item) => Container(
height: 150.0,
decoration: BoxDecoration(
),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
left(item['PlaceId'].toString()) // convert item['placeId'] to String
middle(item['IataCode']),
right()
],
),
);
这篇关于Flutter:当我尝试访问 JSON 数据元素时出现 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!