Skip to content

Instantly share code, notes, and snippets.

@ThinkDigitalSoftware
Last active March 11, 2020 19:44
Show Gist options
  • Save ThinkDigitalSoftware/60e8e600fc90a289871388c1c777a132 to your computer and use it in GitHub Desktop.
Save ThinkDigitalSoftware/60e8e600fc90a289871388c1c777a132 to your computer and use it in GitHub Desktop.
Adds a simple Bloc delegate that prints events and their calling function.
// don't forget to add `BlocSupervisor.delegate = SimpleBlocDelegate();` to the beginning of your main.dart file.
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SimpleBlocDelegate extends BlocDelegate {
SimpleBlocDelegate() {
debugPrint(
'[INFO] Initializing SimpleBlocDelegate. Logging all Bloc events to the console');
}
/// To benefit fully from this function, have your main event class
/// from each bloc extend the [Event] class from this file.
@override
void onEvent(Bloc bloc, Object event) {
debugPrintSynchronously(
'[INFO] ${event.runtimeType} added to ${bloc.runtimeType}');
if (event is Event) {
debugPrintSynchronously('[INFO] called by ${_getCallingMethod(event)}');
}
super.onEvent(bloc, event);
}
}
class Event {
final StackTrace debugInfo;
Event() : debugInfo = StackTrace.current;
}
String _getCallingMethod(Event event) {
List<String> stackTraceLines = event.debugInfo.toString().split('\n');
final String callingFunction =
stackTraceLines[3].replaceFirst(RegExp(r'#3\s+'), '');
return callingFunction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment