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方法是否是一种糟糕的做法,因为州默认情况下它是私有的,所以也许我不应该删除下划线.