Map user = {};
Future<void> getUser(String idProfile) async {
final response = await ac.getItem("/v2/users/:0", [idProfile]);
if (response.statusCode >= 200 && response.statusCode < 300) {
setState(() {
user = json.decode(response.body);
print(user);
});
}
}
@override
void initState() {
super.initState();
getUser(getCurrentUser());
print(user);
}
With the first print, it returns me the user. However, at the second doesn't. I need to get the user information. How could I do it?
CodePudding user response:
getUser
is a future method, you need to wait until it fetches data from API. While you are using StatefulWidget
, you can show landing indication while it fetch data from API.
If it is inside Column
widget,
if (user.isEmpty) Text("fetching data")
else LoadDataWidget(),
Also you can use ternary operator.
CodePudding user response:
Map user = {};
//Return a user from the function
Future<Map<String, dynamic>> getUser(String idProfile) async {
final response = await ac.getItem("/v2/users/:0", [idProfile]);
if (response.statusCode >= 200 && response.statusCode < 300) {
user = json.decode(response.body) as Map<String, dynamic>;
return user
}
else {
throw Exception();
}
}
// Set the user value in initstate
@override
void initState() {
super.initState();
user = getUser(getCurrentUser());
print(user);
}