Home > Mobile >  Future function call in init flutter doesn't update UI
Future function call in init flutter doesn't update UI

Time:01-04

This is the init state of my class:

List<Webinar> webinarList = [];

  Future<void> fetchWebinars() async {
    webinarList = await context.read<UserRepository>().fetchWebinar();
    print(webinarList);
  }

  @override
  void initState() {
    super.initState();
    fetchWebinars();
  }

I want to display a list in which there's a list of webinars that the user has made and for that I am having a class Upcoming Events which has this init state. Using the webinar List variable (which is a list of webinar type) i can display every info that I want to. Although the webinar is getting printed out on the terminal but list view builder is not displaying anything as webinarList.length equals 0 every time. How can I improve this code to serve the purpose?

CodePudding user response:

At the very least, you need to notify your view that the state changed:

Future<void> fetchWebinars() async {
    webinarList = await context.read<UserRepository>().fetchWebinar();
    print(webinarList);
    setState(() {});
  }

If you want to have different UX for your loading than just the empty screen you had if no webinars were returned, you may want to use a FutureBuilder for a loading animation or spinner.

You can find an example at What is a Future and how do I use it?

CodePudding user response:

You have to put this inside a setState((){}),

setState((){
  webinarList = await context.read<UserRepository>().fetchWebinar();
})

Because,

To see changes in the UI, you have to update the state by calling setState((){}).

CodePudding user response:

You have to add a setState() method to refresh buildcontext of states for update UI

setState((){
  webinarList = await context.read<UserRepository>().fetchWebinar();
})
  • Related