颤抖地将数据映射到模型并使用它

时间:2020-09-28 05:21:47

标签: api flutter dart model mapping

我对扑扑很陌生。我遇到了这个问题,此功能位于Widget Build

Dashboard user = Dashboard();
  Future<Dashboard> setup() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    id = prefs.getInt('id');
    final response = await get('http://localhost/myproject/dashboard/user/$id');
    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      user = Dashboard.fromJson(data);
    }
    return user;
  }

我的模特是:

class Dashboard {
  int id;
  String username;
  Profile profile;

  Dashboard(
      {this.id,
      this.username,
      this.profile,
 });

  Dashboard.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    username = json['username'];
    profile = json['profile'] != null ? new Profile.fromJson(json['profile']) : null;

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['username'] = this.username;
    if (this.profile != null) {
      data['profile'] = this.profile.toJson();
    }
    return data;
  }
}

class Profile {
  String birthday;
  int age;
  Null image;
  String gender;
  Profile(
      {this.birthday,
      this.age,
      this.image,
      this.gender});

  Profile.fromJson(Map<String, dynamic> json) {
    birthday = json['birthday'];
    age = json['age'];
    image = json['image'];
    gender = json['gender'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['birthday'] = this.birthday;
    data['age'] = this.age;
    data['image'] = this.image;
    data['gender'] = this.gender;
    return data;
  }
}

我的小部件:

Container(
 padding: const EdgeInsets.only(left: 10, right: 10),
          child: Column(
              children: [
                 Container(
                    child: (user.profile.age != null)
                       ? Text(
                            user.profile.age.toString(),
                            textAlign: TextAlign.center,
                            style: TextStyle(
                            fontSize: 12.0,
                            fontFamily: 'Open-Sans-Regular',
                            color: Colors.black,
                            ),
                            )
                       : Text(
                           '36',
                           textAlign: TextAlign.center,
                           style: TextStyle(
                           fontSize: 12.0,
                           fontFamily: 'Open-Sans-Regular',
                           color: Colors.black,
                            ),),
                       ),

Stacktrace:

The getter 'age' was called on null.
Receiver: null
Tried calling: age

,我收到此错误: NoSuchMethodError:在空值上调用了吸气剂“年龄”。

我正确初始化了该类。 我使用https://javiercbk.github.io/json_to_dart/自动生成模型。 我做错了什么?请赐教。

1 个答案:

答案 0 :(得分:0)

这是您在空配置文件上调用profile.age,仅当该年龄为空时才检查该配置文件。 另外,请根据您的实际情况考虑使用将来的构建器。