Flutter Redux Tutorial – A simple practical Flutter Redux example

In this Flutter Redux tutorial, we’re gonna introduce main concept of Redux: what it is, how to work with Redux Store, Action, Reducers. Then we will practice to understand all of them with a simple practical Flutter Redux example.

Flutter Redux Overview

Redux

Redux is a state container that helps applications to manage state.
=> Whenever we wanna read the state, look into only one single place – Redux Store.
=> Managing the state could be simplified by dealing with simple objects and pure functions.

Redux Store

Store holds the current state so that we can see it as a single source of truth for our data.

Redux Action

Action is payload of information that is sent to Store using store.dispatch(action).
Action must have a type property that should typically be defined as string constants. It indicates the type of action being performed:

Redux Reducer

Reducer is a pure function that generates a new state based on an Action it receives. These Actions only describe what happened, but don’t describe how state changes.

*Note: Reducer must be a pure function:
=> From given arguments, just calculate the next state and return it.
=> No side effects. No API or non-pure function calls. No mutations.

Flutter Redux

StoreProvider: This is the base Widget that passes the given Redux Store to all descendants that request it. So it should wrap MaterialApp or WidgetsApp.

StoreConnector: This is a descendant Widget that gets the Store from the nearest StoreProvider ancestor. It:
+ converts the store into appropriate value/object/callback with the given converter function
+ passes the value/object/callback to a builder function.

When an action is dispatched and run through the reducer, reducer updates the state, the Widget will be rebuilt with the latest value automatically.
=> We don’t need to manually manage subscriptions or streams.

Practice

Example overview

This is a simple Flutter Redux Application that has:
MyAppState as the main state that is stored inside Redux Store.
– 2 types of Action: 'INCREMENT', 'DECREMENT'.
– One Reducer: counterReducer.

We can increase/decrease the Counter value. App will update UI immediately.

flutter-redux-tutorial-overview

Setup Flutter Redux Project

Open pubspec.yaml in Flutter Project. Add a dependency for redux and flutter_redux:

Run command: flutter packages get.

Full Code

lib/main.dart



By grokonez | August 8, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*