【问题标题】:Flutter: TypeError when I try to access elements of JSON dataFlutter:当我尝试访问 JSON 数据的元素时出现 TypeError
【发布时间】:2020-07-09 04:45:32
【问题描述】:

我正在尝试在动态列表视图上显示 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}]

【问题讨论】:

标签: json api listview flutter dart


【解决方案1】:

文本小部件不能显示 int s,它们只能解释 strings ,所以您的错误来自此代码

  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,
        )
      ),
    );
  }

【讨论】:

  • 如果能解决您的问题,请采纳,谢谢
【解决方案2】:

我认为问题在于 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()
  ],
),

);

【讨论】:

    【解决方案3】:

    关于您的问题,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

    【讨论】:

    • 我会执行你的建议。
    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 2016-05-30
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多