I am very new to flutter. I am having this problem and this function is inside the 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;
}
My model is:
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;
}
}
My widget:
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
and I am getting this error: NoSuchMethodError: The getter 'age' was called on null.
I initialized the class properly.. I used https://javiercbk.github.io/json_to_dart/ for auto generating a model. What I am doing wrong? Please enlighten me.