BlocDelegateBuilder to Union delegate[AOP]

538 阅读1分钟

github.com/felangel/bl…

  • 起因:

写代码时,会去想 事件回调可以和事件分离


  • 实现:
import 'package:bloc/bloc.dart';
class DelegateBuilder extends BlocDelegate{
  List<BlocDelegate> lists=[];

  @override
  onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    lists.forEach((delegate)=>{
      delegate.onEvent(bloc, event)
    });
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    lists.forEach((delegate)=>{
      delegate.onTransition(bloc, transition)
    });
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    lists.forEach((delegate)=>{
      delegate.onError(bloc, error, stacktrace)
    });
  }

  add(List<BlocDelegate> delegates) {
    if (delegates != null)
      lists.addAll(delegates);
  }
}
void startup() async {
  FlutterError.onError = (FlutterErrorDetails details) {
    Zone.current.handleUncaughtError(details.exception, details.stack);
  };
  BlocSupervisor.delegate = DelegateBuilder()
    ..add([PassportDelegate(),SimpleBlocDelegate(), GroupRoleDelegate()])  ;
  // HydratedBlocDelegate.build() 

  runZoned(

And, use Case:

class PassportDelegate extends BlocDelegate{
  @override
  void onEvent(Bloc bloc, Object event) {
    // TODO: implement onEvent
    super.onEvent(bloc, event);
      if (event is IsLoginEvent) {
        throw '未登陆';
      }
      
    
  }
  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    // print(error);
    Toast.show(msg: error);
  }
}

  • Use Case:

点赞,评论时,未登陆跳转 部分操作,需要判断角色,操作和判断角色合适 分离 。。。

  • 问题: 没登陆,没角色, 就不会一起提示的

  • 机制: 运行机制 有两种:
  1. throw 事件停止,走onError 2.一直向下走