Flutterr bloc,如何记录事件更改?

kupeojn6  于 2023-06-30  发布在  Flutter
关注(0)|答案(2)|浏览(161)

我有一段代码可以记录控制台中的状态变化,代码看起来像这样。

class ApplicationBlocObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    log('stateChange(${bloc.runtimeType} ${change.currentState})');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    log('onError(${bloc.runtimeType}, $error, $stackTrace)');
    super.onError(bloc, error, stackTrace);
  }
}

我还需要记录事件,用户可能会在应用程序中启动,我怎么能做到这一点?
我想让它看起来像这样

log('stateChange(${bloc.runtimeType}, event ${something that show event } started. State is ${change.currentState})');
7ajki6be

7ajki6be1#

使用onEvent回调:

@override
    void onEvent(Bloc bloc, Object? event) {
        super.onEvent(bloc, event);
        log(...)
    }

关于可能回调的更多信息,请访问:https://pub.dev/documentation/bloc/latest/bloc/BlocObserver-class.html

zrfyljdw

zrfyljdw2#

使用BlocObserver类。
创建新文件:

import 'package:flutter_bloc/flutter_bloc.dart';
import 'dart:developer';

class GlobalBlocObserver extends BlocObserver {
  @override
  void onEvent(Bloc bloc, Object? event) {
    super.onEvent(bloc, event);
    log('${bloc.runtimeType} $event', name: 'Test log');
  }

  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    log('${bloc.runtimeType} $change', name: 'Test log');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    log('${bloc.runtimeType} $transition', name: 'Test log');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    super.onError(bloc, error, stackTrace);
    log('${bloc.runtimeType} $error $stackTrace', name: 'Test log');
  }
}

main.dart中:

void main() {
  Bloc.observer = GlobalBlocObserver();
  runApp(MyApp());
}

就是这样!

相关问题