我需要从应用程序启动时从共享首选项异步加载已保存的主题。加载后,将占位符替换为两个主题。但是下面的代码失败了,因为即使它加载了多个主题的结果,该应用也始终显示两个主题。
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
final bloc = AppThemeBloc();
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
bloc.getAppThemes();
return buildApp();
}
Widget buildApp() {
return StreamBuilder<List<AppTheme>>(
stream: bloc.subject.stream,
builder: (context, AsyncSnapshot<List<AppTheme>> snapshot) {
if (snapshot.hasData) {
return ThemeProvider(
saveThemesOnChange: true,
loadThemeOnInit: true,
themes: snapshot.data,
child: MaterialApp(
home: ThemeConsumer(
child: HomePage(),
),
),
);
} else {
return ThemeProvider(
saveThemesOnChange: true,
loadThemeOnInit: true,
themes: [
AppTheme.light(),
AppTheme.dark(),
],
child: MaterialApp(
home: ThemeConsumer(
child: HomePage(),
),
),
);
}
});
}
}
答案 0 :(得分:0)
在接收到数据并刷新streambuilder之后,该状态会更新状态,因此将再次执行build函数,从而调用:
bloc.getAppThemes();
再次等待流中的任何数据返回返回占位符主题,将bloc.getAppThemes函数放置在initState函数中:
@override
void initState() {
super.initState();
bloc.getAppThemes();
}