【发布时间】:2020-09-28 05:21:47
【问题描述】:
我对 Flutter 很陌生。我遇到了这个问题,这个函数在 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,
),),
),
堆栈跟踪:
The getter 'age' was called on null.
Receiver: null
Tried calling: age
我收到此错误: NoSuchMethodError:getter 'age' 在 null 上被调用。
我正确地初始化了类.. 我使用https://javiercbk.github.io/json_to_dart/ 自动生成模型。 我做错了什么?请赐教。
【问题讨论】:
-
显示你使用
user值的代码部分。 -
发布堆栈跟踪的前 3-5 帧
-
您使用的是 Dashboard 类而不是 Profile 类,请添加正确的代码以便我们回答您
-
我添加了堆栈跟踪以及我在哪里使用用户值。配置文件类在仪表板类中,我应该创建一个新的单独配置文件类吗?
标签: api flutter dart model mapping