Nothing much, just some simple hooks which I use with flutter_bloc package.
useBloc
looks for a Bloc in your widget tree, similar to context.read
(it is actually just context.read
under the hood).
Widget build(BuildContext context) {
final bloc = useBloc<CounterBloc>();
return TextButton(
onPressed: () => bloc.add(CounterEvent.increment),
child: Text('Increment'),
);
}
useBlocBuilder
looks for a Bloc in your widget tree and rebuilds the widget when its state changes.
If your state is quite complex and you don't want to unnecesary rebuild your widget, consider useBlocSelector
Widget build(BuildContext context) {
final count = useBlocBuilder<CounterBloc, int>();
return Text('$count');
}
You can pass buildWhen
callback, which will decide if the widget needs to be rebuild based on the state.
Widget build(BuildContext context) {
final count = useBlocBuilder<CounterBloc, int>(
buildWhen: (previousCount, currentCount) => currentCount <= 10,
);
return Text('Will only count up to 10: $count');
}
useBlocListener
looks for a Bloc in your widget tree and calls listener
on every state update.
Widget build(BuildContext context) {
useBlocListener((CounterBloc _, int count) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('New counter value: $count')),
);
});
return Text('Updated count will appear in a snackbar');
}
useBlocConsumer
combines useBlocBuilder
and useBlocListener
. It allows you to both listen to state changes and update your UI.
Widget build(BuildContext context) {
final count = useBlocConsumer((CounterBloc _, int count) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('New counter value: $count')),
);
});
return Text('Count: $count');
}
useBlocSelector
can be useful when you have a some complex state, but you only want your widget to rebuild when certain properties change.
Widget build(BuildContext context) {
final (isAuthenticated, user) = useBlocSelector(
(AuthBloc _, AuthState state) => (state.isAuthenticated, state.user),
);
if (!isAuthenticated || user == null) {
return LoginScreen();
}
return HomeScreen(user: user);
}