I am trying to fetch data and display it in my app. I am fetching the data on initState. However I am facing this error:
@override
void initState() {
super.initState();
context.read<UseAuth>().fetchUser();
}
and trying to display the data
Text("${context.watch<UseAuth>().userData.length}")
Then in my provider file I got
late List<User> userData;
fetchUser() async {
var response = await fetchUserData(apiClient);
userData = List<User>.from(
(response.data).map((json) => User.fromJson(json))
);
notifyListeners();
}
How do I make sure my data loads and displays?
Response:
{
"avatar_url": "https://google.com",
"description": "Test",
"id": "0c70bbb5-c3e7-41ac-9c80-5b597449232e",
"nick": "test"
}
CodePudding user response:
make your userData
nullable and in your build method check if userData
is null, show loading else use userData
contents
CodePudding user response:
Hope it would help.
@override
Widget build(BuildContext context) {
final usersList = context.watch<UseAuth>().userData;
if (usersList == null || usersList?.isEmpty == true)
return CircularProgressIndicator();
return Text("${context.watch<UseAuth>().userData.length}");
}
Let me know if the above code doesn't work.
There are other ways to solve this error as well.