启动flutter应用程序时,我在哪里运行初始化代码?

Sim*_*onH 8 flutter

启动flutter应用程序时,我在哪里运行初始化代码?

void main() {

  return runApp(MaterialApp(
    title: "My Flutter App",

    theme: new ThemeData(
        primaryColor: globals.AFI_COLOUR_PINK,
                backgroundColor: Colors.white),

        home: RouteSplash(),

    ));
}
Run Code Online (Sandbox Code Playgroud)

如果我想运行一些初始化代码,比如获取共享首选项,或者(在我的情况下)初始化一个包(并且我需要传入 MaterialApp 小部件的 BuildContext),那么正确的方法是什么?

我应该将 MaterialApp 包装在 FutureBuilder 中吗?还是有更“正确”的方式?

- - - - 编辑 - - - - - - - - - - - - - - - - - - - - - ---------

我现在已经将初始化代码放在RouteSplash()小部件中。但是由于我需要应用程序根的 BuildContext 进行初始化,所以我在 Widgetbuild覆盖中调用了初始化并传入了context.ancestorInheritedElementForWidgetOfExactType(MaterialApp). 因为我不需要在显示启动画面之前等待初始化完成,所以我没有使用Future

Doc*_*Doc 7

执行此操作的一种简单方法是将 调用RouteSplash为启动画面,并在其中执行如图所示的初始化代码。

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
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

和里面 main()

void main() {
  runApp(MaterialApp(
    home: RouteSplash(),
  ));
}
Run Code Online (Sandbox Code Playgroud)

注意:这只是一种方法。FutureBuilder如果你愿意,你可以使用 a 。

  • 感谢你的回复。当有人花时间提供全面的答案时,我们总是会感到感激。我实际上所做的与你的回答类似。将初始化代码放在“RouteSplash()”中,但由于我需要应用程序根目录的“BuildContext”,因此我在“build”覆盖中调用了“_fetchPrefs”的等效项,并传入“context.ancestorInheritedElementForWidgetOfExactType(MaterialApp)”。我正在考虑使其异步,但我认为我不需要等待它完成后再显示启动屏幕。 (2认同)