当我尝试访问JSON数据元素时出现Flutter: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,但是您尝试将其用作字符串.
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()
],
),
);
这篇关于当我尝试访问JSON数据元素时出现Flutter:TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!