Manage the state of your app using Redux || Flutterđź’™

What is the state?

We can say that the state is something (an object) that holds the properties of the widget when it’s built and it might change during the lifetime of the widget!

In Redux, we have 3 main components: Action, Reducer, Store!

Action: Actions can be considered as the user events which contains the information or payload for the Store. In other words, it takes the data from UI and sends it to our Store (Business Logic)

Let’s convert our basic counter application and manage its state using Redux!

Step 1: Create a file to store the functionalities. Let’s call it redux_service.dart

Step 2: Wrap your MaterialApp with StoreProvider and provide the redux store to the entire widget tree!

Step 3: Create a file home.dart for the UI. Create a store variable to access the actions and store!

final store = Store<int>(ReduxActions.counterUpdate, initialState: 0);
Center(
child: StoreConnector<int, String>(
converter: (store) => store.state.toString(),
builder: (context, count) {
return Text(
'The button has been pushed this many times: $count',
style: Theme.of(context).textTheme.headline4,
);
},
),
),

Step 4: Now, we need to do the same on our FloatingActionButton too as we will need the access of store to dispatch the action!

StoreConnector<int, VoidCallback>(
converter: (store) {
return () => store.dispatch(CounterActions.Increment);
},
builder: (context, callback) {
return IconButton(
onPressed: callback,
icon: Icon(Icons.add),
);
},
),

Here’s the entire file for home.dart:

Output:

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhishek Doshi

Abhishek Doshi

1.92K Followers

Google Developer Expert — Dart, Flutter & Firebase 💙💛