示例状态:
abstract class ExampleState extends Equatable {
const ExampleState();
}
class LoadingState extends ExampleState {
//
}
class LoadedState extends ExampleState {
//
}
class FailedState extends ExampleState {
//
}
示例事件:
abstract class ExampleEvent extends Equatable {
//
}
class SubscribeEvent extends ExampleEvent {
//
}
class UnsubscribeEvent extends ExampleEvent {
//
}
class FetchEvent extends ExampleEvent {
//
}
示例区块:
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();
}
}
}
}
示例屏幕:
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();
}