返回

前端框架Flutter之Bloc学习手册(三)

前端

BLoC 架构

BLoC 是一种状态管理框架,它将应用程序的状态与 UI 分离。它基于反应式编程和行为驱动开发的思想,强调应用程序的响应性和可测试性。

BLoC 架构的核心思想是将应用程序的状态封装在称为 BLoC 的对象中。BLoC 对象是一个事件流,它负责处理来自 UI 的事件,并根据这些事件更新应用程序的状态。

BLoC 的核心概念

  • BLoC 对象: BLoC 对象是 BLoC 架构的核心。它是一个事件流,负责处理来自 UI 的事件,并根据这些事件更新应用程序的状态。
  • 事件: 事件是 BLoC 对象接收的输入。事件可以来自 UI 交互、网络请求或其他应用程序组件。
  • 状态: 状态是 BLoC 对象维护的应用程序的当前状态。状态可以是任何类型的数据,例如 UI 的当前状态、网络请求的结果或应用程序的设置。
  • 输出: 输出是 BLoC 对象发出的通知,用于更新 UI 或其他应用程序组件。输出可以是任何类型的数据,例如 UI 状态更新、网络请求结果或应用程序设置的更改。

BLoC 的使用场景

BLoC 特别适合于以下场景:

  • 需要将应用程序的状态与 UI 分离
  • 需要提高应用程序的响应性
  • 需要提高应用程序的可测试性
  • 需要在多个组件之间共享状态

BLoC 的完整实例

下面是一个使用 BLoC 来管理应用程序状态的完整实例。

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(0);

  @override
  Stream<int> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.increment:
        yield state + 1;
        break;
      case CounterEvent.decrement:
        yield state - 1;
        break;
    }
  }
}

enum CounterEvent { increment, decrement }

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterBloc(),
      child: BlocBuilder<CounterBloc, int>(
        builder: (context, state) {
          return Column(
            children: [
              Text('Count: $state'),
              Row(
                children: [
                  ElevatedButton(
                    onPressed: () =>
                        BlocProvider.of<CounterBloc>(context).add(CounterEvent.increment),
                    child: const Text('Increment'),
                  ),
                  ElevatedButton(
                    onPressed: () =>
                        BlocProvider.of<CounterBloc>(context).add(CounterEvent.decrement),
                    child: const Text('Decrement'),
                  ),
                ],
              ),
            ],
          );
        },
      ),
    );
  }
}

在这个实例中,我们创建了一个名为 CounterBloc 的 BLoC 对象,它负责管理应用程序的计数器状态。CounterBloc 对象接收两种类型的事件:CounterEvent.incrementCounterEvent.decrement。当 CounterEvent.increment 事件被触发时,CounterBloc 对象将计数器状态增加 1。当 CounterEvent.decrement 事件被触发时,CounterBloc 对象将计数器状态减少 1。

我们还创建了一个名为 CounterPage 的页面,它使用 BlocProviderBlocBuilder 来访问和更新 CounterBloc 对象的状态。当 CounterPage 被构建时,它将创建一个 CounterBloc 对象并将其存储在 BlocProvider 中。BlocBuilder 组件将监听 CounterBloc 对象的状态,并在状态发生变化时更新 UI。

通过使用 BLoC,我们将应用程序的状态与 UI 分离,提高了应用程序的响应性和可测试性。