Flutter Redux With Examples

In this tutorial we will learn about Flutter Redux with some examples. It is very useful package in flutter. Most of flutter developer prefer this to use in the project.

Flutter Redux
Flutter Redux

How to install Redux in Flutter?

To install Redux in flutter using the following command in terminal:

$flutter pub add flutter_redux

Or you can directly add it in the pubspecy.yml file as below:

dependencies:
  flutter_redux: ^0.10.0

Redux is a set of utilities that allows us to easily consume the Redux widget store.

Now, after completing the installation process, import the following library in which class you want to use it.

import 'package:flutter_redux/flutter_redux.dart';

What is Redux In Flutter?

Redux is a state management architecture library that successfully distributes data across the widgets in the repeated manner.

Want to learn more about Redux.

Is Redux good for Flutter?

It contains and provides the fundamental tools required to used Redux in Flutter applications including the store that will be used to define the initial state of the store.

What are Redux actions?

When a state is store, there are widgets and sub-widgets around the application that monitor this state and current values. An action is the object that determines what action is perform on that state.

Flutter Redux Architecture.

store

This is the center location within which the application state exists. The store holds information about the whole application state, or any other single state at every given time.

Redux Widgets


  • StoreProvider – The base widget. It will pass the given Redux store to all the descendants that request it.
  • StoreBuilder – A descendent widget that gets the Store from StoreProvider and passes it to the widget builder function.
  • StoreConnector – A descendent widget that gets the Store from the nearest StoreProvider ancestor, converts the store into the ViewModel with the given converter function. and passes the ViewModel to a builder function. Any time the store emits a change event, the widget will automatically rebuilt. No needed to manage subscriptions.

Example

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';

// One simple action: Increment
enum Actions { Increment }

// The reducer, which takes the previous count and increments it in response
// to an Increment action.
int counterReducer(int state, dynamic action) {
  return action == Actions.Increment ? state + 1 : state;
}

void main() {
  // Create your store as a final variable in the main function or inside a
  // State object. This works better with Hot Reload than creating it directly
  // in the `build` function.
  final store = Store<int>(counterReducer, initialState: 0);

  runApp(FlutterReduxApp(
    title: 'Flutter Redux Demo',
    store: store,
  ));
}

class FlutterReduxApp extends StatelessWidget {
  final Store<int> store;
  final String title;

  FlutterReduxApp({Key key, this.store, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // The StoreProvider should wrap your MaterialApp or WidgetsApp. This will
    // ensure all routes have access to the store.
    return StoreProvider<int>(
      // Pass the store to the StoreProvider. Any ancestor `StoreConnector`
      // Widgets will find and use this value as the `Store`.
      store: store,
      child: MaterialApp(
        theme: ThemeData.dark(),
        title: title,
        home: Scaffold(
          appBar: AppBar(title: Text(title)),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Connect the Store to a Text Widget that renders the current
                // count.
                //
                // We'll wrap the Text Widget in a `StoreConnector` Widget. The
                // `StoreConnector` will find the `Store` from the nearest
                // `StoreProvider` ancestor, convert it into a String of the
                // latest count, and pass that String  to the `builder` function
                // as the `count`.
                //
                // Every time the button is tapped, an action is dispatched and
                // run through the reducer. After the reducer updates the state,
                // the Widget will be automatically rebuilt with the latest
                // count. No need to manually manage subscriptions or Streams!
                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.display1,
                    );
                  },
                )
              ],
            ),
          ),
          // Connect the Store to a FloatingActionButton. In this case, we'll
          // use the Store to build a callback that will dispatch an Increment
          // Action.
          //
          // Then, we'll pass this callback to the button's `onPressed` handler.
          floatingActionButton: StoreConnector<int, VoidCallback>(
            converter: (store) {
              // Return a `VoidCallback`, which is a fancy name for a function
              // with no parameters and no return value. 
              // It only dispatches an Increment action.
              return () => store.dispatch(Actions.Increment);
            },
            builder: (context, callback) {
              return FloatingActionButton(
                // Attach the `callback` to the `onPressed` attribute
                onPressed: callback,
                tooltip: 'Increment',
                child: Icon(Icons.add),
              );
            },
          ),
        ),
      ),
    );
  }
}
copied to clipboard

Learn more simple examples.

Purpose of Redux In Flutter

Everyone have the question why we use Redux when we are using simple Widgets and classes?

Creating an E-Commerce app in Flutter then we have a Cart Screen which will show the cart data. We can add, update and remove the items from other screens where the Cart is appears. For adding, updating and removing items from the Cart, we needed Redux to manage the logics and UI, Because we needed to update the Cart screen after performing any type of activity. For this Redux is used.

Similar patterns in Android are the MVP pattern or using RX Observables to manage a View’s state.

Flutter Redux Vs Flutter Bloc

  • Redux uses a global store so all of your application state is represented in a single state.
  • Bloc distributes the application state across multiple blocs.
  • Bloc stands for “Business Logic Component“.
  • You don’t have to write reducer, actions etc. for the Flutter Bloc.

Thank You for visiting the tutorial on FlutterTPoint. For any doubt and query, you can ask in the comment section below. Learn more useful Flutter Tutorials which will help you to improve your Flutter Development skills.

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment