【问题标题】:Flutter Bloc - is there a way to provide different instances of a bloc in a screenFlutter Bloc - 有没有办法在屏幕中提供不同的块实例
【发布时间】:2021-12-13 04:11:42
【问题描述】:

我有一个名为 FoodCubit 的腕尺,它有两个功能:

-getAllFoods()

-getFilteredFoods(类别)

我有一个像下面这样的屏幕

如您所见,屏幕顶部是一个块生成器,它返回由我的第一个函数发出的状态,该函数在 didChangeDependency() 中调用 底部是同一个 FoodCubit 的另一个 blocbuilder,我想返回第二个函数发出的状态 但是 top blocbuilder 和 bottom blocbuilder 的结果是一样的。我在提供 FoodCubit 的材料应用程序的父级中使用了 blocprovider。如果有一种方法可以提供同一块的两个实例并使用它,我正在徘徊。 有些喜欢

MultiBlocProvider(
Providers:[
//first bloc provider
BlocProvider(), 
//second bloc provider
BlocProvider() 
)

但是我怎样才能在 blocbuilder 中达到它??

我认为一种解决方法是在屏幕的顶部和底部使用两个 blocprovider,但这不会破坏使用 bloc 的目的。 有什么办法吗? 有没有更好的办法?

【问题讨论】:

    标签: flutter dart bloc flutter-bloc flutter-cubit


    【解决方案1】:

    您可以在这里尝试几个选项:

    1. 创建集团的子类:
    class FirstBloc extends FoodCubit {}
    class SecondBloc extends FoodCubit {}
    
    1. 创建集团的 mixin:
    mixin FirstBloc on Bloc {}
    
    mixin SecondBloc on Bloc {}
    
    class FoodCubit extends Bloc with FirstBloc, SecondBloc {
      getAllFoods()
    
      getFilteredFoods(category)
    }
    // Then in your widget
    ... 
    BlocProvider<FirstBloc>(
         create: (_) => FoodCubit(),
         child:
    ...
    BlocProvider<SecondBloc>(
         create: (_) => FoodCubit(),
         child:
    ...
    

    【讨论】:

    • 谢谢,但在 mixin 方法中,我如何调用原始 cubit 中提供的函数。没有任何功能存在:context.read() 除了 Cubit 的默认功能外没有其他功能
    【解决方案2】:

    您可以为两个事件发出相同的状态,即有一个“全部”列表一个“过滤”列表。

    您也不需要两个 BlocBuilder,它可能只是一个。

    【讨论】:

    • 我发出相同的状态是状态数据不同,其中一个被过滤。并且不能是一个 blocbuilder 调度两个不同的事件,它们的结果显示在两个不同的地方
    猜你喜欢
    • 1970-01-01
    • 2019-05-27
    • 2021-01-06
    • 2020-09-06
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多