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
There are a few strategies.
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().