【发布时间】:2020-10-20 04:55:33
【问题描述】:
example_states:
abstract class ExampleState extends Equatable {
const ExampleState();
}
class LoadingState extends ExampleState {
//
}
class LoadedState extends ExampleState {
//
}
class FailedState extends ExampleState {
//
}
example_events:
abstract class ExampleEvent extends Equatable {
//
}
class SubscribeEvent extends ExampleEvent {
//
}
class UnsubscribeEvent extends ExampleEvent {
//
}
class FetchEvent extends ExampleEvent {
//
}
example_bloc:
class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
@override
ExampleState get initialState => LoadingState();
@override
Stream<ExampleState> mapEventToState(
ExampleEvent event,
) async* {
if (event is SubscribeEvent) {
//
} else if (event is UnsubscribeEvent) {
//
} else if (event is FetchEvent) {
yield LoadingState();
try {
// network calls
yield LoadedState();
} catch (_) {
yield FailedState();
}
}
}
}
example_screen:
class ExampleScreenState extends StatelessWidget {
// ignore: close_sinks
final blocA = ExampleBloc();
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<ExampleBloc, ExampleState>(
bloc: blocA,
// ignore: missing_return
builder: (BuildContext context, state) {
if (state is LoadingState) {
blocA.add(Fetch());
return CircularProgressBar();
}
if (state is LoadedState) {
//...
}
if (state is FailedState) {
//...
}
},
),
);
}
}
正如您在 example_bloc 中看到的,初始状态是 LoadingState(),在构建中它显示圆形进度条。我使用 Fetch() 事件来触发下一个状态。但是我在那里使用它感觉不舒服。我想做的是:
当应用程序启动时,它应该显示 LoadingState 并开始网络调用,然后当它全部完成时,它应该显示 LoadedState 和网络调用结果,如果出现问题,它应该显示 FailedState。我想不做就实现这些
if (state is LoadingState) {
blocA.add(Fetch());
return CircularProgressBar();
}
【问题讨论】:
标签: flutter dart bloc flutter-bloc