在Flutter应用中立即显示应用主题 [英] Display app theme immediately in Flutter app
问题描述
鉴于Flutter shared_prefs插件的异步特性,如何确保启动应用程序后立即显示正确的主题设置? IE. shared_prefs完成加载后,不会闪烁默认主题,然后应用正确的主题.
Given the asynchronous nature of the Flutter shared_prefs plugin, how could one make sure that when an app is launched the correct theme settings are immediately displayed? I.e. no flash of the default theme followed by applying the correct theme once the shared_prefs have finished loading.
推荐答案
When your build
method requires waiting for a Future
, it's a good time to break out FutureBuilder
.
void main() {
runApp(new FutureBuilder(
future: SharedPreferences.getInstance(),
builder: (_, snapshot) {
return snapshot.hasData ?
new MyApp(preferences: snapshot.data) :
new LoadingScreen();
},
));
}
使用这种模式构建应用程序的一些技巧:
A few tips for building apps with this pattern:
-
SharedPreferences.getInstance()
非常快.空的Container
作为黑色的加载屏幕,而不是闪烁的彩色内容,您的应用看起来可能会更好.但是,如果您同时加载其他内容,则显示徽标更为合理.
SharedPreferences.getInstance()
is pretty fast. You app may look better with an emptyContainer
as a black loading screen instead of a flash of colorful content. However, if you're loading other stuff at the same time, showing your logo makes more sense.
如果您需要等待多个期货,可以使用
Future.wait 或将多个FutureBuilder
嵌套在一起.
If you need to await multiple futures, you can use
Future.wait or nest multiple FutureBuilder
s together.
这篇关于在Flutter应用中立即显示应用主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!