鉴于 Flutter shared_prefs 插件的异步特性,如何确保在启动应用程序时立即显示正确的主题设置? IE。在 shared_prefs 完成加载后,不闪烁默认主题,然后应用正确的主题。
最佳答案
当您的 build
方法需要等待 Future
时,正是突破 FutureBuilder
的好时机.
void main() {
runApp(new FutureBuilder(
future: SharedPreferences.getInstance(),
builder: (_, snapshot) {
return snapshot.hasData ?
new MyApp(preferences: snapshot.data) :
new LoadingScreen();
},
));
}
使用这种模式构建应用程序的一些技巧:
SharedPreferences.getInstance()
非常快。您的应用可能会使用一个空的 Container
作为黑色加载屏幕而不是一闪而过的彩色内容看起来更好。但是,如果您同时加载其他内容,则显示您的 Logo 更有意义。
如果你需要等待多个future,你可以使用
Future.wait或将多个 FutureBuilder
嵌套在一起。
https://stackoverflow.com/questions/44379849/