当我尝试访问JSON数据元素时出现Flutter:TypeError

时间:2020-03-28 15:51:43

标签: json api listview flutter dart

我正在尝试在动态列表视图中显示JSON数据的各个元素。但是,我不断收到“类型'int'不是类型'String'的子类型”错误,我也不知道为什么。

如果在buildFlightsColumn函数的Row下的窗口小部件中仅包含left()函数,则该代码有效。但是,一旦包含了middle()和right()函数,我就会得到错误。

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数据:

[{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}]

3 个答案:

答案 0 :(得分:1)

文本窗口小部件无法显示int,它们只能使字符串交织,因此您的错误来自此代码

  Widget buildFlightsColumn(dynamic item) => Container( 
    height: 150.0, 
    decoration: BoxDecoration(
    ),
    child: new Row( 
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[ 
        left(item['PlaceId']) // item['placeId'] is int,
        middle(item['IataCode']),
        right()
      ],
    ),
  );

  Container left(dynamic item) {
    return new Container (
      child: Text(   
        item, // here item is int, which is not allowed <-----------------------
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 25.0,
          color: Colors.red,
        )
      ),
    );
  }

您可以使用.toString()方法或字符串插值将其编号更改为字符串


  Container left(dynamic item) {
    return new Container (
      child: Text(   
        item.toString(), // here item is String <-----------------------
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 25.0,
          color: Colors.red,
        )
      ),
    );
  }

答案 1 :(得分:0)

我认为问题在于PlaceId的类型为int,但是您尝试将其用作字符串。

像这样更改代码:

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()
  ],
),

);

答案 2 :(得分:0)

出现问题时,Flutter Text小部件仅接受String数据类型。 尝试使用x.toString()int转换为String或在“文本”小部件中使用"$x""${x}"

说实话,像在Flutter代码中一样使用JSON对象实际上是一个不好的做法。您应该考虑进行序列化和反序列化,因为它可以提高鲁棒性。简单来说,反序列化意味着将您的JSON转换为类对象,而序列化则相反。这是flutter文档的示例。

class User {
  final String name;
  final String email;

  User(this.name, this.email);

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}

强烈建议使用此技术来更好地控制数据及其数据类型。

Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap); // convert json to obj

print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');

String json = jsonEncode(user); // convert obj to json

有关此主题的更多信息:https://flutter.dev/docs/development/data-and-backend/json