Home > Software engineering >  How to read fetched data from API?
How to read fetched data from API?

Time:12-25

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:

enter image description here

 @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.

  • Related