问题描述
启动Flutter应用程序时,我在哪里运行初始化代码?
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(),
));
}
如果我想运行一些初始化代码来获取共享的首选项,或者(对于我而言)初始化一个包(并且我需要传递MaterialApp小部件的BuildContext),那么正确的方法是这?
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?
我应该将MaterialApp包装在FutureBuilder中吗?还是有一种更正确"的方式?
Should I wrap the MaterialApp in a FutureBuilder? Or is there a more 'correct' way?
-------编辑---------------------------------------------------
------- EDIT ---------------------------------------------------
我现在已将初始化代码放在 RouteSplash()
小部件中.但是由于需要初始化应用程序根目录的BuildContext,因此我在Widget build
覆盖中调用了初始化,并在 context.ancestorInheritedElementForWidgetOfExactType(MaterialApp)
中进行了传递.由于我不需要等待初始化完成即可显示初始屏幕,因此我没有使用 Future
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
推荐答案
一种简单的方法是调用 RouteSplash
作为初始屏幕,并在其内部执行所示的初始化代码./p>
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
),
);
}
}
和 main()
void main() {
runApp(MaterialApp(
home: RouteSplash(),
));
}
注意:这只是其中一种方法.如果需要,可以使用 FutureBuilder
.
Note: It is just one way of doing it. You could use a FutureBuilder
if you want.
这篇关于启动Flutter应用程序时应在哪里运行初始化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!