我最近一直在将旧代码转换为BLOC 8. 1版本,我遇到了下一个问题。应用程序是多线程的,mapEventToState方法运行出流,重要的是,yield使用。示例:
BlocBuilder<NewsBloc, NewsState>(builder: (context, state) {
switch (state.status) {
case NewsStatus.failure:
return const Center(
child: Text('FAILD'));
case NewsStatus.newMessage:
return messageList(objNews);
case NewsStatus.success:
return messageList(objNews);
default:
return const Center(child: CircularProgressIndicator());
}
}
问题是他在(mapEventToState)上需要一个未来,而我需要它是有收益的流。
新闻集团
class NewsBloc extends Bloc<NewsEvent, NewsState> {
NewsBloc(...)
super(NewsState()) {
on<NewsEvent>(mapEventToState);
}
@override
Stream<NewsState> mapEventToState(NewsEvent event) async* {
if (event is NewsInitial) {
yield await mapNewsInitialToState(state);
}
if (event is NewsFetched) {
yield await _mapNewsFetchedToState(state);
}
if (event is MessageReceived) {
yield await _mapMessageReceivedToState(state, event);
}
if (event is NewsClear) {
yield await mapNewsClearToState(state);
}
if (event is MessageRead) {
yield await mapMessageReadToState(state, event);
}
}
}
Future<ChatListState> mapNewsInitialToState(NewsState state) async {
try {
final rooms = await services!.getRoomsList();
return state.copyWith(
status: NewsStatus.success,
rooms: rooms,
state: state
);
} catch (e, s) {
print('$e, stacktrace: $s');
return state.copyWith(status: NewsStatus.failure,state: state);
}
}
新闻州
enum NewsStatus { initial, success, failure, newMessage }
class NewsState extends Equatable {
NewsStatus? status;
List<NewsRoom>? rooms;
bool? hasReachedMax;
bool? isNew;
NewsState({
this.status = NewsStatus.initial,
this.rooms = const <NewsRoom>[],
this.hasReachedMax = false,
this.isNew = false,
});
NewsState copyWith({
@required NewsStatus? status,
@required List<NewsRoom>? rooms,
@required bool? hasReachedMax,
@required bool? isNew,
required NewsState state
}) {
state.status = status ?? this.status ;
state.rooms = rooms ?? this.rooms;
state.hasReachedMax = hasReachedMax ?? this.hasReachedMax;
state.isNew = isNew ?? this.isNew ;
return state;
}
@override
String toString() {
return '''NewsState { status: $status, hasReachedMax: $hasReachedMax, rooms: ${rooms!.length}, isNew: $isNew, }''';
}
@override
List<Object?> get props => [status, rooms, hasReachedMax, isNew];
}
class MessageReceivedState extends NewsState {
final ChatMessage? chatMessage;
MessageReceivedState({@required this.chatMessage});
@override
List<Object?> get props => [chatMessage];
}
有没有人知道如何同时保留一个流,以便代码符合BLOC8.1?
1条答案
按热度按时间a0x5cqrl1#
BLoC 8使用
Emitter
,而不是使用yield
的Stream
s。请尝试更改mapEventToState
签名并将yield
替换为Emitter
调用。它应该大致如下所示: