Handling application state is not straightforward in Flutter. Good news that we can add Redux library to flutter.

This is a guide on how to add redux to your flutter app.

Add Redux Dependency

In pubspec.yaml file, add the following dependencies:

dependencies:
  flutter:
    sdk: flutter
    .... // Other dependencies
  flutter_redux: ^0.5.3
  redux_thunk: ^0.2.1

As of the current writing, the above versions are available for redux. We will be using redux_thunk library to further simplify reducers.

Add Redux Store to App

For every redux application, we need to initialize the Redux store that will handle the current application state.

// main.dart

import 'package:redux/redux.dart';
import 'package:redux_thunk/redux_thunk.dart';
import 'package:my_app/App.dart';
import 'package:my_app/AppState.dart';

static AppState rootReducer(AppState state, dynamic action) {
  print('action.runtimeType=${action.runtimeType}');
  state.messageString = 'Message string updated';
  return state;
}

void main() {
  var initialState = AppState();
  final Store<AppState> store = Store<AppState>(
     rootReducer,
     initialState: initialState,
     middleware: [thunkMiddleware],
  )
  runApp(MyApp(store: store));
}

In the main.dart file, we need to create the redux store which is called by using Store<AppState>. AppState class defines the model of the state. You can make your own model whatever fits your requirements.

You can also create an initial state for the redux when the app launches. For example, you can change the value of messageString after creating the AppState model.

Don’t get confused with thunkMiddleware. It is provided by redux_thunk library which you don’t need to go to your reducer to dispatch another action again. You can directly put the function name and redux_thunk automatically calls the function you passed during dispatch.

// App.dart

class MyApp extends StatelessWidget {
  final Store<AppState> store;

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

  void callDispatchFunction(Store<AppState> store) async {
     // Do any async calls here or any logic that may require calls to backend etc.
  }

  @override
  Widget build(BuildContext context) {

    store.dispatch(this.callDispatchFunction);

    return StoreProvider<AppState>(
      child: MaterialApp(
       // Parameters for MaterialApp
      ),
      store: store,
    );
  }
}

In the code above, MateriaApp widget is usually the root widget for any flutter application. However, if you want to use redux, StoreProvider is usually the root widget that you will need to use in order to make your state available to all widgets.

// AppState.dart

class AppState {
  String messageString;
}

Try this out. Using redux will most likely help you with any application-wide state such as accessing settings, etc.

Leave a Reply

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