CategoryTagArticle

admin

I'm a Full-stack developer

Tag

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
State management with redux in Flutter
Published date: 14/06/2023

In this article, I will show an example to manage the state in the Flutter application using Redux. For JavaScript developers, Redux is not a sublime and not a new thing. What is it? You will learn about it with me. !!!


What is Redux?


Redux is like other tools for state management. It makes the application work consistently, run in different environments, and be easy to test and debug.

Redux contains 3 components: Action, Store, and Reducers. You should understand these definitions.




  • Action: It is events to change the state of the application and is also the only way to change those states through store.dispatch()
  • Reducer: Responsible for creating new states from an existing state of the application from an action above.
  • Store: Used to store application states and it is unique.


Below will be an operating principle of a Redux.



Redux in Flutter


In Flutter, there are 2 useful packages, easy to implement: redux and flutter_redux.




  • StoreProvider: The base widget for the app that will be used to provide the Store for all the Widgets that need it.
  • StoreBuilder: A widget used to get store from StoreProvider
  • StoreConnector: A very useful widget used as an alternative to StoreBuilder, which converts the Store into a ViewModel with the given conversion function, and converts the ViewModel into a builder function. Whenever the Store emits a change event, the Widget is automatically rebuilt. No need to manage subscriptions!


How to use Redux in the Flutter application?


To understand Redux in Flutter, let's take a look at the example below:


When the user taps add button (+) or decreases button (-), the number of products to buy to add to the cart. After adding a new (from 0 to 1) or deleting a product (from 1 to 0), immediately the total number of products in the cart on the tabbar will be changed accordingly.


For example, in the figure, when adding a new one it goes from 4 to 5, and when it is deleted it goes from 4 to 3.


Next, below will be the steps to implement the code for the application like the example above.



  • Add the package to the file pubspec.yaml
dependencies:
  redux: ^5.0.0
  flutter_redux: ^0.10.0


Create a redux folder to contain files related to actions, reducers, selectores, ...




  • store.dart file
import 'reducers.dart';

Store<AppState> createReduxStore() {
  return Store<AppState>(
    appStateReducers,
    initialState: AppState.initial(),
    middleware: [],
  );
}




  • reducers.dart file
AppState appStateReducers(AppState state, dynamic action) {
  return AppState(
      cartItems: cartReducer(state.cartItems, action));
}




  • actions/cart.dart file
class SetCartItems {
  final List<CartModel> cartItems;

  SetCartItems(this.cartItems);
}

class SetUpdateCartItem {
  final CartModel item;

  SetUpdateCartItem(this.item);
}




  • reducers/cart.dart file
final cartReducer = combineReducers<List<CartModel>>([
  TypedReducer<List<CartModel>, SetCartItems>(_setCartItems),
  TypedReducer<List<CartModel>, SetUpdateCartItem>(_updateCartItem),
]);

List<CartModel> _setCartItems(List<CartModel> state, SetCartItems action) {
  return state;
}

List<CartModel> _updateCartItem(
    List<CartModel> state, SetUpdateCartItem action) {
  return state;
}




  • selectors/cart.dart file
int getTotalCartItem(AppState state) {
  return state.cartItems.length;
}




  • Modify main.dart file
void main() {
  Store<AppState> store = createReduxStore();

  runApp(App(store: store));
}




  • Modify app.dart file
class App extends StatelessWidget {
  final Store<AppState> store;

  const App({super.key, required this.store});

  @override
  Widget build(BuildContext context) {
    return StoreProvider<AppState>(
        store: store,
        child: MaterialApp(
          title: 'Đinh Thành Công',
          theme: ThemeData(),
          initialRoute: '/',
          routes: {
          },
          onUnknownRoute: (RouteSettings setting) {
            return MaterialPageRoute(
                builder: (context) => const NotFoundScreen());
          },
        ));
  }
}


At this point, you and I have finished configuring a Redux corresponding to the example above. Next, how to display the number as shown in the picture. Let's go:



  • screens/products.dart file
class ProductsScreenState extends State<ProductsScreen> {
  @override
  void initState() {
    super.initState();
  }

  int _getTotalPrice() {
    final store = StoreProvider.of<AppState>(context);

    return getTotalPrice(store.state);
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, List<CartModel>>(
        builder: (context, cartItems) {
          return Scaffold(
              body: ListView.builder(
                shrinkWrap: true,
                primary: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: cartItems.length,
                itemBuilder: (BuildContext context, int index) {
                  return Text('Product name');
                },
              ));
        },
        converter: (store) => store.state.cartItems);
  }
}


At this point, we just need to re-build the application and wait for the results.


I hope this article is of great value to you. Good luck !!!!

Recommend

Create Project with Express + TypeScript + ESLint + Auto Reload
admin12/06/2023

Create Project with Express + TypeScript + ESLint + Auto Reload
In this article, I introduce to you how to initialize an Express + TypeScript project.
TypeScript Design Pattern - Singleton
admin07/08/2023

TypeScript Design Pattern - Singleton
The singleton ensures only a single install is created in a class and provides a method to access this instance everywhere in a codebase.
Data structure: Singly Linked List
admin07/04/2024

Data structure: Singly Linked List
In this article, I will show you how to set up a singly linked list algorithm in Python.
Newest

Form validator in Flutter with EzValidator
admin04/01/2024

Form validator in Flutter with EzValidator
When I am working on Flutter with form. For ensuring data integrity, and handling user input errors. I want to show an error message below each TextField, Dropdown, Switch, ... if the user does not input or wrong input. The EzValidator help me to resolve this.
TypeScript Design Pattern - Builder
admin07/08/2023

TypeScript Design Pattern - Builder
TypeScript Design Pattern - Builder
Part 1: React Props and State
admin18/06/2023

Part 1: React Props and State
Before learning React, we should understand Props and State. This is basic for a newbie.
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Feedback
Name
Phone number
Email
Content
Download app
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About