Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
State management with redux in Flutter
Ngày đăng: 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 !!!!

Đề xuất

Design Patterns
admin07/08/2023

Design Patterns
The design pattern does not be a specific programming language. Almost programming languages might apply design patterns that to resolve a problem repeat.
TypeScript Design Pattern - Abstract Factory
admin07/08/2023

TypeScript Design Pattern - Abstract Factory
The abstract factory pattern is one of five design patterns in the Creational Design Pattern group. The abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.
Microservice in a Monorepo
admin22/06/2023

Microservice in a Monorepo
Microservice in a Monorepo
Mới nhất

🚀 Using Bitwise Oprators to build a RBAC in Node.js 🚀
admin13/04/2024

🚀 Using Bitwise Oprators to build a RBAC in Node.js 🚀
In this article, I will illustrate to you how to build an RBAC in Node.js using Bitwise Operators.
Part 3: React Fragments
admin18/06/2023

Part 3: React Fragments
In this part, I will show you about good benefits when using fragments in React.
Semantic Versioning NodeJS
admin07/07/2023

Semantic Versioning NodeJS
How to Use Semantic Versioning in NPM
Đ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
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About