Title

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
July 15, 2023

Flutter Redux: State Management Made Easy

Introduction

When it comes to state management in Flutter, developers have a wide range of options to choose from. One popular choice is the Redux library, which provides a predictable state container that can be easily integrated into Flutter applications. In this tutorial, we will explore how to implement Redux in a Flutter project and leverage its powerful features for managing application state.

Setting up Redux

To get started with Redux, we need to add the flutter_redux package to our project's dependencies. Open the pubspec.yaml file and add the following lines:


dependencies:
  flutter:
    sdk: flutter
  flutter_redux: ^0.8.2
  redux: ^4.0.0

After adding the package, run flutter packages get to install it.

Implementing Redux

The core concept in Redux is the Store which holds the application state. The state is represented by a Reducer function that takes the current state and an Action and returns a new state. Let's go ahead and define our state and actions.


// Define the state
class CounterState {
  final int count;
  
  CounterState(this.count);
}

// Define the actions
enum CounterActions { Increment, Decrement }

Next, we need to create our reducer function:


CounterState counterReducer(CounterState state, dynamic action) {
  if (action == CounterActions.Increment) {
    return CounterState(state.count + 1);
  } else if (action == CounterActions.Decrement) {
    return CounterState(state.count - 1);
  }
  
  return state;
}

Creating the Store

Now that we have our state and reducer, let's create the Redux store and wire everything together. In your main.dart file, add the following code:


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

void main() {
  final store = Store<CounterState>(counterReducer, initialState: CounterState(0)); // Create the store
  
  runApp(MyApp(store: store));
}

class MyApp extends StatelessWidget {
  final Store<CounterState> store;
  
  MyApp({required this.store});

  @override
  Widget build(BuildContext context) {
    return StoreProvider<CounterState>(
      store: store,
      child: MaterialApp(
        title: 'Flutter Redux',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StoreConnector<CounterState, int>(
      converter: (store) => store.state.count, // Extract count from the store
      builder: (context, count) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Redux'),
          ),
          body: Center(
            child: Text('Count: $count'),
          ),
          floatingActionButton: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                onPressed: () => StoreProvider.of<CounterState>(context).dispatch(CounterActions.Increment),
                child: Icon(Icons.add),
              ),
              SizedBox(height: 16),
              FloatingActionButton(
                onPressed: () => StoreProvider.of<CounterState>(context).dispatch(CounterActions.Decrement),
                child: Icon(Icons.remove),
              ),
            ],
          ),
        );
      },
    );
  }
}

In the above code, we create the Redux store using the counterReducer and the initial state of 0. The MyHomePage widget subscribes to the store using the StoreConnector widget, which rebuilds whenever the state changes. The state is then passed to the widget using the builder function.

Summary

In this tutorial, we explored how to integrate Redux into a Flutter application for managing state. We learned how to define the state and actions, create a reducer function, and set up the Redux store. By leveraging the power of Redux, developers can easily manage complex application states and ensure consistent and predictable behavior throughout their Flutter projects.

Redux