在我的 flutter 應用程式中,我使用flutter_bloc進行狀態管理。
該bloc問題使用repository。該repository訂閱到WebSocket,而新資料添加到流。
問題:我的集團監聽流:
InvestmentClubBloc({
required this.investmentClubRepository
}) : super(InvestmentClubLoading()) {
onChangeSubscription = investmentClubRepository.onNewMessage.listen(
(event) {
emit(NewMessageState(event); // <-- The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test
},
);
}
問題是這emit不起作用(我收到警告“成員“emit”只能在‘package:bloc/src/bloc.dart’或在測驗中使用”)
bloc 如何監聽流并根據流事件發出新狀態?
uj5u.com熱心網友回復:
您應該使用emitin eventHandler,使用以下代碼來完成您的任務:
abstract class Event {}
class DemoEvent extends Event {}
var fakeStream =
Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15);
class DemoBloc extends Bloc<Event, int> {
DemoBloc() : super(0) {
fakeStream.listen((_) {
// add your event here
add(DemoEvent());
});
on<DemoEvent>((_, emit) {
// emit new state
emit(state 1);
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374708.html
