skip to Main Content

I have a pretty simple problem. I have a code snippet that looks like this:

class home_page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Main();
}

class Main extends State<home_page> {
 void initState() {
    super.initState();
  }
 @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    double height = MediaQuery.of(context).viewPadding.top;
    return Text('hello')
  }
}

I want to call a function that makes a get request to a local server, lets say ‘localhost:3000/getsomething’ and then after a response is gotten, I want to process that response, and then assign it to a variable. Then after that process is complete, I want to load the app. In the meantime, I want to show a loading icon that takes up the entire screen.

Here is a visual:

class home_page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Main();
}

class Main extends State<home_page> {
 var response;
 void initState() {
    loadData();
    super.initState();
  }

  void loadData() async {
    await //GET REQUEST
    response = //GET REQUEST RESPONSE
    //SHOW THE ACTUAL APP AND GET RID OF THE LOADING ICON
  }
 @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    double height = MediaQuery.of(context).viewPadding.top;
    return Text('hello')
  }
}

Thank you so much!

2

Answers


  1. There are a few strategies.

    1. You can run the awaited items in an async main(), before you call runApp().
    2. You can call runApp on just a spinner, then do #1. (Yes, calling runApp twice is supported!
    3. If you have Riverpod providers that need warming up, you can do that as part of main, or as part of a top-level widget. I have videos that show both in my https://www.youtube.com/@RandalOnDartAndFlutter youtube channel.
    Login or Signup to reply.
  2. If you need to make a request before MaterialApp, then you can create a SplashPage() page with StatefulWidget and make it the initial page.

    In it, you can set the variable bool isLoading = true and show the loading indicator. When loadData() called in initState returns a result, then call setState(() => isLoading = false). Only it is better to call loadData() after super.initState().

    And the result can be stored in the cache or using Get It or similar.

    In fact, there are many different ways to do this. You could use a FutureBuilder if you want.

    And if you just need to make a request for one page, as it looks like in the code given in the question, then just use FutureBuilder or do the same as in SplashPage().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search