Flutter 块模式中的状态不屈服

state not yield in Flutter bloc pattern

我正在使用 flutter_bloc 包在 flutter bloc patter 中构建一个测试应用程序。问题是只呈现 Event1 的状态,但代码在 mapEventToState 中执行。我认为问题出在 yield 语句上,因为在触发 Event2 时,mapEventToState Executes 中的相应打印语句。

mapEventTOState函数在page_bloc.dart

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");
                      }                       
                    },
                  )

Scaffold中的悬浮动作按钮如下:

floatingActionButton: FloatingActionButton(
        onPressed: () => pageBlocInstace2..add(Event2()),
        child: Icon(Icons.done),
      ),

而脚手架中的另一个小部件如下:

GestureDetector(
        onTap: () => pageBlocInstace1..add(Event1()),
        child: Center(child: Text("Tap to here")));

这个问题是因为两个事件调用了不同的 bloc 实例。

floatingActionButton: FloatingActionButton(
        onPressed: () => pageBlocInstace..add(Event2()),
        child: Icon(Icons.done),
      ),

GestureDetector(
        onTap: () => pageBlocInstace..add(Event1()),
        child: Center(child: Text("Tap to here")));