Search code examples
flutterdartasynchronousfuture

Future function call in init flutter doesn't update UI


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?


Solution

  • 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?