繁体   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