前言

flutter经过了几年的发展,现在的Bloc 在实现上也有了更新,这里重新梳理对Bloc的理解。

关键主题

  • BlocProvider,一个为其子widget提供bloc的Flutter widget
  • BlocBuilder,处理widget响应新状态的widget
  • Cubit vs Bloc,两者之间的区别
  • 通过 context.read 添加events
  • Equatable,用于避免无必要的对widget重新构建的依赖库
  • RepositoryProvider为其子widget提供 repository 的widget
  • BlocListener,在bloc中调用监听代码执行状态变更响应的widget

    创建Repository

    创建Repository的目的是为了存储指定需要管理的对象的状态的变更。
    例如为了存储授权状态,则需要创建一个名为authentication_repository.dart的文件。 ```dart import ‘dart:async’;

enum AuthenticationStatus { unknown, authenticated, unauthenticated }

class AuthenticationRepository { final _controller = StreamController();

Stream get status async { await Future.delayed(const Duration(seconds: 1)); yield AuthenticationStatus.unauthenticated; yield _controller.stream; }

Future logIn({ required String username, required String password, }) async { await Future.delayed( const Duration(milliseconds: 300), () => _controller.add(AuthenticationStatus.authenticated), ); }

void logOut() { _controller.add(AuthenticationStatus.unauthenticated); }

void dispose() => _controller.close(); } `` 可以看到,上面的代码中有Stream`StreamController,因此可以了解bloc实际是基于Stream实现的。
在authentication_repository.dart里定义了login和logOut方法,用于通知应用程序,当用户登入或登出时会执行状态更新。
对于StreamController,需要显示的声明一个dispose方法,这样controller可以在不再使用时被关闭。

注意

但是,现在的Bloc不再是最佳方案,目前flutter已经维护并提供了provider支持对Widget的状态进行管理。

参考