Simon Hutton
Simon Hutton

Reputation: 1777

Where do I run initialisation code when starting a flutter app?

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

Upvotes: 17

Views: 14731

Answers (2)

Doc
Doc

Reputation: 11651

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.

Upvotes: 14

Jack Lillie
Jack Lillie

Reputation: 13

To run code at startup, put it in your main.dart. Personally, that's the way I do it, to initialise lists etc.

Upvotes: -3

Related Questions