Skip to content

Commit

Permalink
chore: add bloc observer, set up zone guards
Browse files Browse the repository at this point in the history
  • Loading branch information
thisissandipp committed Jun 28, 2024
1 parent 32197d0 commit cc88179
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 20 deletions.
23 changes: 23 additions & 0 deletions lib/app_bloc_observer.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'dart:developer';
import 'package:bloc/bloc.dart';

/// {@template app_bloc_observer}
/// Custom instance of [BlocObserver] which logs
/// any state changes and errors.
/// {@endtemplate}
class AppBlocObserver extends BlocObserver {
/// {@macro app_bloc_observer}
const AppBlocObserver();

@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}

@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
}
38 changes: 18 additions & 20 deletions lib/bootstrap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,30 @@ import 'dart:async';
import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:sudoku/app_bloc_observer.dart';

class AppBlocObserver extends BlocObserver {
const AppBlocObserver();

@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}

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

/// Bootstrap is responsible for any common setup and calls
/// [runApp] with the widget returned by [builder] in an error zone.
Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
// Log all uncaught build phase errors from the framework
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};

Bloc.observer = const AppBlocObserver();

// Add cross-flavor configuration here
// Log all uncaught asynchronous errors that aren't handled
// by the Flutter framework.
PlatformDispatcher.instance.onError = (error, stack) {
log(error.toString(), stackTrace: stack);
return true;
};

runApp(await builder());
await runZonedGuarded(
() async {
Bloc.observer = const AppBlocObserver();
runApp(await builder());
},
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
}

0 comments on commit cc88179

Please sign in to comment.