gpt4 book ai didi

flutter - Flutter block 模式中的状态不屈服

转载 作者:行者123 更新时间:2023-12-03 03:11:41 24 4
gpt4 key购买 nike

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

page_bloc.dart中的ma​​pEventTOState函数

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中的悬 float 作按钮如下:

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

关于flutter - Flutter block 模式中的状态不屈服,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60956271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com