[英]how can i make bloc available for all flutter app pages
I am using bloc to manage my app state, I want to provide the bloc for all my app pages so I have inserted in the top of the widget tree so I can use it from any place in the widget tree, I have used it as the follows我正在使用 bloc 来管理我的应用程序 state,我想为我的所有应用程序页面提供 bloc,因此我已将其插入到小部件树的顶部,以便我可以从小部件树中的任何位置使用它,我已将其用作以下
1- main page 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- 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) {
.......
},));}}
but the flutter display an error that但 flutter 显示错误
BlocProvider.of() called with a context that does not contain a Bloc of type MyBloc
and this is a screenshot of the app's widgets tree这是应用程序小部件树的屏幕截图
, what is the error, I want to provide mybloc for all widgets ,什么是错误,我想为所有小部件提供 mybloc
note: the app run ok if I write the MainPage class and the secondPage class in the same page, but when I separate them the error appears注意:如果我在同一页面中写入 MainPage class 和 secondPage class,应用程序运行正常,但是当我将它们分开时出现错误
I was shocked by the solution, the problem was only in import, I have replaced我对解决方案感到震惊,问题仅在导入中,我已更换
import '../blocs/blocs.dart';
With和
import 'package: loony_trips / blocs / blocs.dart';
And everything was fixed, even though the two sentences were supposed to be the same一切都是固定的,即使这两个句子应该是一样的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.