简体   繁体   English

Flutter:BLoC 包 - 块提供者

[英]Flutter: BLoC package - bloc provider

I'm using this package: https://pub.dartlang.org/packages/bloc .我正在使用这个包: https : //pub.dartlang.org/packages/bloc I have 2 views: In the first one I display a list of elements using "bloc1" and, trough a FloatingActionButton, I can navigate to a second screen that uses "bloc2".我有两个视图:在第一个视图中,我使用“bloc1”显示元素列表,并且通过 FloatingActionButton,我可以导航到使用“bloc2”的第二个屏幕。 In this second screen I want to add an element to my previous list trough a Bloc provider of "bloc1", so that I can do something like bloc1.dispatch(addElement) .在第二个屏幕中,我想通过“bloc1”的 Bloc 提供者向我之前的列表添加一个元素,以便我可以执行类似bloc1.dispatch(addElement) My question is: how can I declare a bloc provider of bloc1?我的问题是:如何声明 bloc1 的 bloc 提供者? For example something like: Bloc bloc = BlocProvider.of<Bloc1>(context)例如类似: Bloc bloc = BlocProvider.of<Bloc1>(context)

You would need to wrap your MaterialApp with BlocProvider like:您需要使用 BlocProvider 包装您的 MaterialApp,例如:

BlocProvider(bloc: bloc1, child: MaterialApp(...));

Then you can access bloc1 from anywhere using: BlocProvider.of<Bloc1>(context)然后你可以从任何地方访问 bloc1 使用: BlocProvider.of<Bloc1>(context)

Hope that helps!希望有帮助!

Bloc now supports MultiBlocProvider which helps you setup all your blocs once in the main and use it anywhere in your code. Bloc 现在支持 MultiBlocProvider,它可以帮助您在 main 中一次设置所有 bloc,并在代码中的任何地方使用它。

In your main.dart在你的 main.dart

return MultiBlocProvider(
  providers: [
    BlocProvider<BlocA>(create: (BuildContext context) => BlocA(),),
    BlocProvider<BlocB>(create: (BuildContext context) => BlocB(),),
  ],
  child: MaterialApp(....),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM