Skip to content

evaqum/bloc_hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Bloc Hooks

Nothing much, just some simple hooks which I use with flutter_bloc package.

Hooks

useBloc

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

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

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

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

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);
}

About

Hooks which I use in my personal projects

Resources

Stars

Watchers

Forks

Languages