Flutter state management with bloc pattern

Udith Shalinda
3 min readDec 22, 2019

--

When the scale of your flutter app gets higher or when you wants to share application states between screens across the application, it’s better if you can use state management pattern. For that you can use bloc pattern or provider library.

Let’s talk about bloc pattern here.

First we need to have these dependencies.

dependencies:   
bloc: ^2.0.0
flutter_bloc: ^2.0.0
equatable: ^0.6.0

In here I’m going to show you how to manage the state string list.

To create a simple todo list,first you need to have a model.

To manage the state,NameState.dart file

Like the initialTodo state you can add any states as you wish.

The event file will look like this.

In AddTodoEvent we need to pass a Todo instance.In UpdateTodoEvent I get the index of the todo element from the todo list.

In the TodoBloc file you need to override the initial state as you want.Using if ladder we can execute different methods like I did above.

In _mapAddTodoToState method I add a Todo to the existing list.And by “yield” we can change the state or the state’s data. You can read the state property of the state as state.something.

In ui ,If you have only one Bloc then you can use BlocProvider.

home: Scaffold(         
appBar: AppBar(
title: Text('Posts'),
),
body: BlocProvider(
create: (context) =>
PostBloc(httpClient: http.Client())..add(Fetch()),
child: HomePage(),
),
),

If you have multiple blocs to deal with ,then you can use below approach.

You can use MultiBlocProvider.And you can use your widget as child component of the multiBlocProvider.

You can show the todo list using listView builder like above.

Thank you!

--

--