flutter_hooks_bloc 0.9.0 flutter_hooks_bloc: ^0.9.0 copied to clipboard
A flutter_bloc reimplementation based on flutter_hooks with the same API.
flutter_hooks_bloc #
A flutter_bloc reimplementation based on flutter_hooks for
BlocBuilder
, BlocListener
, BlocConsumer
and MultiBlocListener
.
Usage #
MultiBlocListener, BlocBuilder, BlocListener and BlocConsumer
They work exactly the same as the original. See the flutter_bloc
documentation.
useBloc
The useBloc
hook function allows to listen state changes and rebuild
the widget if necessary.
C useBloc<C extends Cubit<S>, S>({
/// cubit to subscribe. if it is null, it will be infered
C cubit,
/// If `onEmitted` is not provided or its invocation returns `true`,
/// the widget will rebuild.
BlocHookListener<S> onEmitted,
});
It can be used into a HookBuilder:
HookBuilder(builder: (ctx) {
print('HookBuilder');
final counter = useBloc<CounterCubit, int>(
onEmitted: (_, prev, curr) {
print('listener: $prev $curr');
return true;
}
).state;
return Text(
'$counter',
style: Theme.of(context).textTheme.headline4,
);
});
And also into a widget that extends a HookWidget:
class BlocBuilder<C extends Cubit<S>, S> extends HookWidget
with CubitComposer<C>, BlocBuilderInterface<C, S> {
const BlocBuilder({
Key key,
this.cubit,
@required this.builder,
this.buildWhen,
}) : assert(builder != null),
super(key: key);
@override
final C cubit;
@override
final BlocWidgetBuilder<S> builder;
@override
final BlocBuilderCondition<S> buildWhen;
@override
Widget build(BuildContext context) {
final _cubit = useBloc<C, S>(
cubit: cubit,
onEmitted: (context, previous, state) {
return buildWhen?.call(previous, state) ?? true;
}
);
return builder(context, _cubit.state);
}
}