feat(bloc): add init function and multi provider

This commit is contained in:
2022-10-17 19:56:23 -04:00
parent b99664856d
commit 2807582a16
6 changed files with 145 additions and 15 deletions
@@ -28,7 +28,7 @@ import 'package:wyatt_bloc_helper/src/utils/smart_provider.dart';
/// It automatically handles closing the instance when used with [create].
/// By default, [create] is called only when the instance is accessed.
/// To override this behavior, set [lazy] to `false`.
///
///
/// By default, it provide already provided instance found in the tree.
/// To override this behavior, set [smart] to `false`.
/// {@endtemplate}
@@ -47,13 +47,21 @@ abstract class BlocBaseProviderScreen<Bloc extends BlocBase<State>,
final bool lazy;
/// Whether this uses [SmartProvider].
/// Defaults to `true`. But if you want to provide new [Bloc] or [Cubit]
/// Defaults to `true`. But if you want to provide new [Bloc] or [Cubit]
/// of a same type in a sub-tree you may have to disable this.
final bool smart;
/// Creates the [Bloc] or [Cubit] to be used.
Bloc create(BuildContext context);
/// Initialize the [Bloc] or [Cubit].
///
/// This function is useful when using with [SmartProvider], because
/// if you want to pass an initial event to your bloc you can pass it in
/// `create` function but if you re-use the bloc below in the tree this event
/// will never be re-pass.
Bloc init(BuildContext context, Bloc bloc) => bloc;
/// Creates the child [Widget] to be used.
Widget builder(BuildContext context);
@@ -63,6 +71,7 @@ abstract class BlocBaseProviderScreen<Bloc extends BlocBase<State>,
lazy: lazy,
enable: smart,
create: (_) => create(context),
init: (_, bloc) => init(context, bloc),
child: Builder(builder: builder),
);
}
@@ -40,7 +40,6 @@ abstract class BlocBaseScreen<Bloc extends BlocBase<State>,
/// accessed the first time, not when provided.
final bool lazy;
/// Whether this uses [SmartProvider].
/// Defaults to `true`. But if you want to provide new Bloc of a same type,
/// in a sub-tree you may have to disable this.
@@ -49,12 +48,21 @@ abstract class BlocBaseScreen<Bloc extends BlocBase<State>,
/// Creates the [Cubit] or [Bloc] to be used.
Bloc create(BuildContext context);
/// Initialize the [Bloc] or [Cubit].
///
/// This function is useful when using with [SmartProvider], because
/// if you want to pass an initial event to your bloc you can pass it in
/// `create` function but if you re-use the bloc below in the tree this event
/// will never be re-pass.
Bloc init(BuildContext context, Bloc bloc) => bloc;
@override
Widget build(BuildContext context) => SmartProvider.bloc<Bloc, State>(
context,
lazy: lazy,
enable: smart,
create: (_) => create(context),
child: super.build(context),
);
context,
lazy: lazy,
enable: smart,
create: (_) => create(context),
init: (_, bloc) => init(context, bloc),
child: super.build(context),
);
}