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

Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
admin17/06/2023

Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
You are a beginner with Ghost CMS, Bitanami, AWS Lightsail and don't know much about the documentation yet. So, in this article, I introduce step by step to upgrade Ghost CMS to the latest version.
Part 4: How to use Redux Toolkit in React
admin18/06/2023

Part 4: How to use Redux Toolkit in React
In this article, I will explain Redux and delve into Redux Toolkit. a collection of tools that simplify using Redux. These tools help make Redux less daunting and easier to use.
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.
Mới nhất

Microservice in a Monorepo
admin22/06/2023

Microservice in a Monorepo
Microservice in a Monorepo
JOI - API schema validation
admin12/06/2023

JOI - API schema validation
Data validation is one of topics that I am interesting. I always review my code after developed features or fixed bugs. There are many places where need to validate data, it is really terrible. Some cases, we need to validate data input because ensure the data into API, it will not make any problems to crash system.
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.
Đ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