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.
TypeScript Design Pattern - Adapter
admin08/08/2023

TypeScript Design Pattern - Adapter
This design pattern acts as a bridge between two different interfaces.
How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
Mới nhất

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.
Part 2: Setup Custom Domain Zone + SSL for Ghost on AWS Lightsail
admin17/06/2023

Part 2: Setup Custom Domain Zone + SSL for Ghost on AWS Lightsail
In this section, I will continue to show you how to point Ghost Instance Static IP to your domain.
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.
Đ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