2

我正在使用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");
                      }                       
                    },
                  )

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

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

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

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

1 回答 1

5

这个问题是由于这两个事件调用了单独的 bloc 实例。

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

GestureDetector(
        onTap: () => pageBlocInstace..add(Event1()),
        child: Center(child: Text("Tap to here")));
于 2020-03-31T18:00:50.477 回答