Where do I run initialisation code when starting a flutter app?
void main() {
return runApp(MaterialApp(
title: "My Flutter App",
theme: new ThemeData(
primaryColor: globals.AFI_COLOUR_PINK,
backgroundColor: Colors.white),
home: RouteSplash(),
));
}
If I want to run some initialisation code to, say fetch shared preferences, or (in my case) initialise a package (and I need to pass in the the BuildContext of the MaterialApp widget), what is the correct way to do this?
Should I wrap the MaterialApp in a FutureBuilder? Or is there a more 'correct' way?
------- EDIT ---------------------------------------------------
I have now placed the initialisation code in RouteSplash()
widget. But since I required the BuildContext of the app root for the initialisation, I called the initialisation in the Widget build
override and passed in context.ancestorInheritedElementForWidgetOfExactType(MaterialApp)
. As I don't need to wait for initialisation to complete before showing the splash screen, I haven't used a Future
Invoke View > Command Palette. Type “flutter”, and select the Flutter: New Project. Select Application.
Open VSCode and invoke the command palette via View Command Palette… or Ctrl + Shift + P. Select Flutter: New Application Project. Use flutterui as name for your project.
One simple way of doing this will be calling the RouteSplash
as your splash screen and inside it perform the initialization code as shown.
class RouteSplash extends StatefulWidget {
@override
_RouteSplashState createState() => _RouteSplashState();
}
class _RouteSplashState extends State<RouteSplash> {
bool shouldProceed = false;
_fetchPrefs() async {
await Future.delayed(Duration(seconds: 1));// dummy code showing the wait period while getting the preferences
setState(() {
shouldProceed = true;//got the prefs; set to some value if needed
});
}
@override
void initState() {
super.initState();
_fetchPrefs();//running initialisation code; getting prefs etc.
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: shouldProceed
? RaisedButton(
onPressed: () {
//move to next screen and pass the prefs if you want
},
child: Text("Continue"),
)
: CircularProgressIndicator(),//show splash screen here instead of progress indicator
),
);
}
}
and inside the main()
void main() {
runApp(MaterialApp(
home: RouteSplash(),
));
}
Note: It is just one way of doing it. You could use a FutureBuilder
if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With