首页 > 解决方案 > 类的对象没有在 Flutter 的循环中实例化

问题描述

我正在使用json.decode将我的 JSON 数据转换为 Objects 类型User。我在FutureFutureBuilder部件中使用以下内容。这是代码。

Future<List<User>> _getData() async {
    var data = await http.get("http://www.json-generator.com/api/json/get/cvAgrXxhOW?indent=2");
    var jsonBody = json.decode(data.body);

    List<User> users = [];

    for (var user in jsonBody) {
      print(user);
      User u = new User(user); 
      users.add(u);
    }

    print(users.length);

    return users;
}

User 类看起来如下所示。

class User {
  String _id;
  int index;
  String about;
  String name;
  String picture;
  String gender;
  int age;
  String registered;
  double longitude;
  String email;
  String eyeColor;
  String phone;
  String address;
  double latitude;
  String balance;
  String guid;
  String company;
  bool isActive;

  User(dynamic data){
    this._id = json.decode(data)["_id"];
    this.index = int.parse(json.decode(data)["index"]);
    this.about = json.decode(data)["about"];
    this.name = json.decode(data)["name"];
    this.picture = json.decode(data)["picture"];
    this.gender = json.decode(data)["gender"];
    this.age = int.parse(json.decode(data)["age"]);
    this.registered = json.decode(data)["registered"];
    this.longitude = double.parse(json.decode(data)["longitude"]);
    this.email = json.decode(data)["email"];
    this.eyeColor = json.decode(data)["eyeColor"];
    this.phone = json.decode(data)["phone"];
    this.address = json.decode(data)["address"];
    this.latitude = double.parse(json.decode(data)["latitude"]);
    this.balance = json.decode(data)["balance"];
    this.guid = json.decode(data)["guid"];
    this.company = json.decode(data)["company"];
    this.isActive = json.decode(data)["isActive"];
  }

  getUser(){
    return this;
  }
}

该行User u = new User(user);不允许代码进一步执行。函数中的print语句_getData()仅适用于循环的第一次迭代。之后,什么也没有发生。没有错误。

有什么建议么?

标签: classdartflutter

解决方案


哟不需要decode再次数据

尝试这个:

User(dynamic data){
    this._id = data["_id"];
    this.index = int.parse(data["index"]);
    this.about = data["about"];
    ....

更新

var jsonBody = json.decode(data.body) as List;

最终更新 我发现了错误,您不需要解析为 int 或 double 它已经解析,因为它是一个动态对象。

    User(Map<String, dynamic> data) {
      this._id = (data)["_id"];
      this.index = data["index"];
      this.about = (data)["about"];
      this.name = (data)["name"];

      this.picture = (data)["picture"];
      this.gender = (data)["gender"];
      this.age = (data)["age"];
      this.registered = (data)["registered"];
      this.longitude = data["longitude"];
      this.email = (data)["email"];
      this.eyeColor = (data)["eyeColor"];
      this.phone = (data)["phone"];
      this.address = (data)["address"];
      this.latitude = (data)["latitude"];
      this.balance = (data)["balance"];
      this.guid = (data)["guid"];
      this.company = (data)["company"];
      this.isActive = (data)["isActive"];
    }

推荐阅读