我对flutter是个新手。我遇到了这个问题,这个函数在Widget构建中
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:在null上调用了getter 'age‘。
我正确地初始化了类..我使用https://javiercbk.github.io/json_to_dart/自动生成模型。我做错了什么?请给我开导一下。
发布于 2020-09-28 18:40:03
这是在一个空配置文件上调用profile.age,只有当该年龄为空时,您才不会检查该配置文件。此外,根据您具体在做什么,考虑使用未来的构建器。
https://stackoverflow.com/questions/64096340
复制相似问题