【发布时间】:2020-07-30 11:02:53
【问题描述】:
我正在使用 bloc 来管理我的应用程序状态,我想为我的所有应用程序页面提供 bloc,因此我已插入到小部件树的顶部,以便我可以从小部件树中的任何位置使用它,我有如下使用它
1- 主页
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}}
class MyAppState extends State<MyApp>{
@override
Widget build(BuildContext context) {
return BlocProvider<MyBloc>(
create: (BuildContext context) {
return MyBloc();
},
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: secondPage()),
);
}
}
2-秒页:
class SecondPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return SecondPage State();
}
}
class SecondPage State extends State<SecondPage > {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('secondPage')),
body: BlocBuilder<CityBloc, CityState>(
builder: (BuildContext context, CityState state) {
.......
},));}}
但颤振显示错误
BlocProvider.of() called with a context that does not contain a Bloc of type MyBloc
,什么是错误,我想为所有小部件提供 mybloc
注意:如果我在同一页面中编写 MainPage 类和 secondPage 类,应用程序运行正常,但是当我将它们分开时会出现错误
【问题讨论】: