I'm trying to learn how to execute some code in a BLoC listener depending on the state and a code variable that's only present in the success state.
I would like to be able to tell if I'm on the Success state from the Listener, and also, access It's current code

以下是我所在的集团成员国:

@freezed
class ExampleState with _$ExampleState {
  const factory ExampleState.initial() = _Initial;
  const factory ExampleState.success(int code) = _Success;
  const factory ExampleState.error() = _Error;
}

和欧盟

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() : super(_Initial()) {
    on<_ChangeCode>((event, emit) {
      if(state is _Success){
        int stateCode = (state as _Success).code;
        debugPrint("Ey, I got the current code:  $stateCode");
        //Would like to access this code variable in a similar way in the listener
      }
      emit(ExampleState.success(event.newCode));
    });
  }
}

最后,这是监听ExampleBloc的监听程序:

listener: (context, state) {
               //Would like to check if the state is success

               //Would like to print something if the state.code == 5
              },

我找到的解决方案如下:

将code变量添加到所有州,这样我就可以执行"state.code"

@freezed
class ExampleState with _$ExampleState {
  const factory ExampleState.initial(int code) = _Initial;
  const factory ExampleState.success(int code) = _Success;
  const factory ExampleState.error(int code) = _Error;
}

然后我可以做:

 listener: (context, state) {
    debugPrint(state.code.toString());
 },

I don't really like this solution as it is really annoying to use on the long run.
-
The other option, would be removing the underscore of the state that I want to check, like so:

@freezed
class ExampleState with _$ExampleState {
  const factory ExampleState.initial() = _Initial;
  const factory ExampleState.success(int code) = Success;
  const factory ExampleState.error() = _Error;
}

然后我可以做:

 listener: (context, state) {
   if(state is Success){
     debugPrint(state.code.toString());
   }
 },

但我不知道Second方法是否是一种糟糕的做法,因为州默认情况下它是私有的,所以也许我不应该删除下划线.

推荐答案

您冻结的类是一个"联合类型",您可以使用名为maybeWhenwhen的方法来处理不同的状态,因此您可以简单地执行以下操作:

listener: (context, state) {
   state.when(
     initial: () {...},
     success: (int code) {...},
     error: () {...}
   );
},

Flutter相关问答推荐

Flutter -修改子小部件中的AppBar

Flutter:InteractiveViewer中可伸缩SVG背景上的定位小部件不对齐

Box约束强制无限高:SizedBox. Expand()

在fltter_widget_from_html中启动url

如何在容器小部件中的图像旁边添加文本?

如何使用Dio/Ffltter(前端)和amp;Go(后端)向API发送正确的请求

如何使页面浏览量达到活动页面所要求的高度?

如何让经过Firebase身份验证的用户能够将Zip文件上载到Firebase云存储?

Firebase WHERE过滤器在日期字段中不起作用

如何在flutter中更改showModalBottomSheet小部件中CheckboxListTile小部件的值?

如何使用 Material3 创建带有高度的完美白色提升按钮?

FutureProvider 不返回数据给 UI

在 flutter 中获取最喜欢的文档

转换函数上传文件上传Uint8List

使用 Riverpod 和 copyWith 方法更新数据类中列表中变量的值

在 Flutter 中使用 HardwareKeyboard 时所有键都没有响应

如何在 flutter 中创建渐变按钮

如何在Flutter 中根据其父小部件高度设置图标按钮飞溅半径

Flutter NavigationBar 忽略我的背景 colored颜色

是否可以在 Flutter 中使用 ToggleButtons 在页面 PageView 之间切换?