Flutter Redux :
Flutter redux is a uni directional data flow architecture for easy development of apps.This way of app development will also make it easy to test as well.
In this tutorial we will be seeing the most easiest way of understanding the concept of Redux pattern.Redux pattern is very much helpful for even testing.
Flutter redux patterns will make use of actions, reducers, store, state and finally update UI depending upon the requirement.
We have discussed each and every step how a redux will help us in managing the state with the help of the above mentioned components in the video tutorial provided.
We have gone through various tutorials on flutter state management in our previous blogs may refer them for more interesting ways of managing the state.
pubspec.yaml :
Add the dependency flutter_redux and update to latest version available so as to avoid unwanted issues.
dependencies: flutter: sdk: flutter flutter_redux: ^0.8.2
main.dart :
In this tutorial we are making use of a simple concept like increment and decrement so as to make it easy to understand.
We will beĀ storing the data in the store which is a centralized data center from where we perform operations with the help of reducers by creating actions and finally emitting them as results.
Store connectors are used in the below example to fetch the data dispatch the actions.
So here the actions are increment and decrement.
import 'package:flutter/material.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:redux/redux.dart'; enum Actions { inc, dec } int counterReducer(int count, dynamic action){ if(action == Actions.inc) { return count + 1; } else if(action == Actions.dec){ return count - 1; } return count; } void main(){ final store = Store<int>(counterReducer, initialState: 0); runApp(MyApp( store : store )); } class MyApp extends StatelessWidget { final Store<int> store; const MyApp({Key? key, required this.store}) : super(key: key); @override Widget build(BuildContext context) { return StoreProvider(store: store, child: MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Redux Example"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ StoreConnector<int, String>(builder: (context, count){ return Text("Count is $count"); }, converter: (store) => store.state.toString()), StoreConnector<int, VoidCallback>(builder: (context, callback){ return TextButton(onPressed: callback, child: const Text("Increment")); }, converter: (store){ return () => store.dispatch(Actions.inc); }), StoreConnector<int, VoidCallback>(builder: (context, callback){ return TextButton(onPressed: callback, child: const Text("Decrement")); }, converter: (store){ return () => store.dispatch(Actions.dec); }) ], ), ), ), )); } }
If you have any queries in this tutorial on flutter redux do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates.