簡體   English   中英

Riverpod:如何將 StateNotifier 與 Maps 一起使用並更新 UI?

[英]Riverpod: How to use StateNotifier with Maps and update the UI?

I want to add/Update Maps to state of StateNotifier and then retrieve length of state as well as update the UI when Map is added to or deleted from the state.

現在,長度在增加和減少,但 UI 沒有更新。

地圖(key = productId,value = Cart,即模型)

class Cart {
  final String dateId;
  final String title;
  final int quantity;
  final double price;

  Cart(
      {required this.dateId,
        required this.title,
        required this.quantity,
        required this.price});
}

class CartNotifier extends StateNotifier<Map<String, Cart>> {
  CartNotifier() : super({});

  int cartLength() {
    return state.length;
  }

  void add(String productId, double price, String title) {
    if (!state.containsKey(productId)) {
      Map<String, Cart> cartMap = {
        productId: Cart(
            dateId: 'dateId', title: title, quantity: 1, price: price),
      };
      state = {...state, ...cartMap};
    } else {
      state.update(
          productId,
              (existing) =>
              Cart(
                dateId: existing.dateId,
                title: existing.title,
                quantity: existing.quantity + 1,
                price: existing.price,
              ));
    }
  }
}

這是我的提供者-

final cartProvider = StateNotifierProvider<CartNotifier, Map<String, Cart>>(
  (ref) => CartNotifier(),
);

這是我在 ConsumerWidget 的構建方法中使用提供程序的地方-

          ElevatedButton(
            onPressed: () {
              ref.read(cartProvider.notifier).add(
                    _idController.text,
                    double.parse(_priceController.text),
                    _titleController.text,
                  );
            },
            child: const Text('Submit'),
          ),
Text('${ref.read(cartProvider.notifier).cartLength()}'),

我們可以使用 Riverpod 設置和獲取數據,鈎子如下所示。 看看這個例子。 鏈接: Flutter Riverpod Statenotifier 應在 map 更改時重建

它只改變了一行代碼-

Text('${ref.watch(cartProvider).length}'),

不是調用 Method,而是調用 ref 的長度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM