我正在使用flutter_bloc软件包在flutter bloc模式中构建一个测试应用程序。问题在于仅渲染了Event1的状态,但是代码在mapEventToState中执行。我认为问题在于yield语句,因为在触发Event2时,mapEventToState中的相应打印语句将执行。
page_bloc.dart中的 mapEventTOState 函数
Stream<PageState> mapEventToState(PageEvent event) async* {
print(event);
if (event is Event1) {
print(">> $event");
yield State10();
try {
await someAsyncFunction();
yield State11(message: "message");
print("reached 100");
} catch (e) {
yield State12();
}
} else if (event is Event2) {
yield State20();
try {
await someAyncFunction2();
yield State21();
} catch (e) {
yield State22(message: e.toString());
}
}
// TODO: implement mapEventToState
}
page_state.dart 如下:
abstract class PageState extends Equatable {
@override
List<Object> get props => [];
}
class State10 extends PageState {}
class State11 extends PageState {}
class State12 extends PageState {}
class State20 extends PageState {}
class State21 extends PageState {}
class State22 extends PageState {}
page_event.dart 在下面给出
abstract class PageEvent extends Equatable {
@override
// TODO: implement props
List<Object> get props => null;
}
class Event1 extends PageEvent {}
class Event2 extends PageEvent {}
BlocBuilder 如下:
child: BlocBuilder<PageBloc, PageState>(
builder: (context, state) {
print(state);
if (state is State10) {
return Text("State10");
} else if (state is State11) {
return Text("State11");
} else if (state is State12) {
return Text("State12");
} else if (state is State20) {
return Text("State20");
} else if (state is State21) {
return Text("State21");
} else if (state is State22) {
return Text("State22");
}
},
)
脚手架中的浮动操作按钮如下:
floatingActionButton: FloatingActionButton(
onPressed: () => pageBlocInstace2..add(Event2()),
child: Icon(Icons.done),
),
支架中的另一个小部件如下:
GestureDetector(
onTap: () => pageBlocInstace1..add(Event1()),
child: Center(child: Text("Tap to here")));
答案 0 :(得分:4)
此问题归因于两个事件调用了单独的bloc实例。
floatingActionButton: FloatingActionButton(
onPressed: () => pageBlocInstace..add(Event2()),
child: Icon(Icons.done),
),
GestureDetector(
onTap: () => pageBlocInstace..add(Event1()),
child: Center(child: Text("Tap to here")));