Red*_*edZ 5 flutter flutter-bloc
我使用 Flutter 和 flutter_bloc 制作一个应用程序,它定期向我的服务器发送 API 请求并请求数据。在我使用计时器实现周期性功能之前,它最初工作得很好,这是我的块文件:
class HomeBeehivesBloc extends Bloc<HomeBeehivesEvent, HomeBeehivesState> {
HomeBeehivesBloc() : super(BeehivesInitial()) {
on<LoadBeehives>((event, emit) => _onBeehivesLoaded(emit));
}
Future<void> _onBeehivesLoaded(Emitter<HomeBeehivesState> emit) async {
emit(BeehivesLoading());
final repository = BeehivesRepository();
const duration = Duration(seconds: 5);
Timer.periodic(duration, (timer) async {
try {
await repository.getHomeBeehives().then((beehives) async {
emit(BeehivesLoadedSuccessfully(beehives: beehives));
});
} catch (exception) {
log(exception.toString());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到了这个例外:
'package:bloc/src/emitter.dart': Failed assertion: line 114 pos 7: '!_isCompleted':
emit was called after an event handler completed normally.
This is usually due to an unawaited future in an event handler.
Please make sure to await all asynchronous operations with event handlers
and use emit.isDone after asynchronous operations before calling emit() to
ensure the event handler has not completed.
**BAD**
on<Event>((event, emit) {
future.whenComplete(() => emit(...));
});
**GOOD**
on<Event>((event, emit) async {
await future.whenComplete(() => emit(...));
});
Run Code Online (Sandbox Code Playgroud)
我尝试到处寻找解决方案,但老实说,这是我第一次使用新版本的 bloc 包(之前从未使用过 emit),我想要一些关于如何解决这个问题的建议。
附带问题:在那里实现周期性计时器是个好主意吗?因为我看到有些人在前端实现它(例如有状态小部件),所以我也希望有任何关于此的建议。
非常感谢!
您的代码不会等待内部回调Timer.periodic完成 - 该_onBeehivesLoaded方法完成执行,因此当回调尝试发出新状态 ( BeehivesLoadedSuccessfully) 时,您会收到此错误。
要解决此问题,您应该向 BLoC 添加一个新事件,并稍后像任何其他 BLoC 事件一样处理它,而不是在回调内发出新状态。
HomeBeehivesLoaded:class HomeBeehivesLoaded extends HomeBeehivesEvent {
final List<Beehive> beehives; // <-- Not sure if Beehive is the right type, just an assumption
const HomeBeehivesLoaded(this.beehives);
}
Run Code Online (Sandbox Code Playgroud)
class HomeBeehivesBloc extends Bloc<HomeBeehivesEvent, HomeBeehivesState> {
HomeBeehivesBloc() : super(BeehivesInitial()) {
<...>
on<HomeBeehivesLoaded>(_onHomeBeehivesLoaded);
}
void _onHomeBeehivesLoaded(HomeBeehivesLoaded event, Emitter<HomeBeehivesState> emit) {
emit(BeehivesLoadedSuccessfully(beehives: event.beehives));
}
<...>
}
Run Code Online (Sandbox Code Playgroud)
Timer.periodic回调中,从存储库获得响应后添加此事件,而不是发出状态:class HomeBeehivesBloc extends Bloc<HomeBeehivesEvent, HomeBeehivesState> {
<...>
Future<void> _onBeehivesLoaded(Emitter<HomeBeehivesState> emit) async {
<...>
Timer.periodic(duration, (timer) async {
try {
await repository.getHomeBeehives().then((beehives) async {
add(HomeBeehivesLoaded(beehives: beehives));
});
} catch (exception) {
log(exception.toString());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3835 次 |
| 最近记录: |