简体   繁体   English

如何在 Riverpod 中显示来自 StateNotifier 的小吃店?

[英]How do I show a snackbar from a StateNotifier in Riverpod?

I have the following class that is working fine.我有以下 class 工作正常。

class CartRiverpod extends StateNotifier<List<CartItemModel>> {

    CartRiverpod([List<CartItemModel> products]) : super(products ?? []);

        void add(ProductModel addProduct) {
            bool productExists = false;
                for (final product in state) {
                    if (product.id == addProduct.id) {
                        print("not added");
                        productExists = true;
                    }
                    else {
                    }
                 }
        if (productExists==false)
            {
                state = [
                    ...state, new CartItemModel(product: addProduct),
                ];
                print("added");
             }

    }

    void remove(String id) {
      state = state.where((product) => product.id != id).toList();
    }
  }

The code above works perfectly.上面的代码完美运行。 In my shopping cart, I want to limit the order of products to just 1 unit, that is why I am doing the code above.在我的购物车中,我想将产品的订单限制为 1 个单位,这就是我执行上面代码的原因。 It works as I expected.它按我的预期工作。 The only thing now is that, I'd like to show a snackbar alerting the user that he or she can only order 1 unit of each product.现在唯一的事情是,我想显示一个快餐栏,提醒用户他或她只能订购每种产品的 1 个单位。

How do I add a snackbar inside my StateNotifier?如何在我的 StateNotifier 中添加快餐栏?

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/all.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart_list_page.freezed.dart';

final cartListPageStateNotifierProvider =
    StateNotifierProvider((ref) => CartListPageStateNotifier(ref.read));

final cartListProvider = StateProvider((ref) {
  return <CartListItemModel>[];
}); // this holds the cart list, at initial, its empty

class CartListPage extends StatefulWidget {
  @override
  _CartListPageState createState() => _CartListPageState();
}

class _CartListPageState extends State<CartListPage> {
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  List<CartListItemModel> productsToBeAddedToCart = [
    CartListItemModel(id: 1, name: "Apple"),
    CartListItemModel(id: 2, name: "Tomatoes"),
    CartListItemModel(id: 3, name: "Oranges"),
    CartListItemModel(id: 4, name: "Ginger"),
    CartListItemModel(id: 5, name: "Garlic"),
    CartListItemModel(id: 6, name: "Pine"),
  ];

  @override
  Widget build(BuildContext context) {
    return ProviderListener<CartListState>(
      provider: cartListPageStateNotifierProvider.state,
      onChange: (context, state) {
        return state.maybeWhen(
          loading: () {
            final snackBar = SnackBar(
              duration: Duration(seconds: 2),
              backgroundColor: Colors.yellow,
              content: Text('updating cart....'),
            );
            return _scaffoldKey.currentState.showSnackBar(snackBar);
          },
          success: (info) {
            final snackBar = SnackBar(
              duration: Duration(seconds: 2),
              backgroundColor: Colors.green,
              content: Text('$info'),
            );
            _scaffoldKey.currentState.hideCurrentSnackBar();
            return _scaffoldKey.currentState.showSnackBar(snackBar);
          },
          error: (errMsg) {
            final snackBar = SnackBar(
              duration: Duration(seconds: 2),
              backgroundColor: Colors.red,
              content: Text('$errMsg'),
            );
            _scaffoldKey.currentState.hideCurrentSnackBar();
            return _scaffoldKey.currentState.showSnackBar(snackBar);
          },
          orElse: () => SizedBox.shrink(),
        );
      },
      child: Scaffold(
        key: _scaffoldKey,
        body: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              SizedBox(height: 40),
              Expanded(
                child: ListView.builder(
                  itemCount: productsToBeAddedToCart.length,
                  itemBuilder: (context, index) {
                    final item = productsToBeAddedToCart[index];
                    return ListTile(
                      title: Text("${item.name}"),
                      leading: CircleAvatar(child: Text("${item.id}")),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          IconButton(
                            icon: Icon(Icons.add),
                            onPressed: () => context
                                .read(cartListPageStateNotifierProvider)
                                .addProduct(item),
                          ),
                          SizedBox(width: 2),
                          IconButton(
                            icon: Icon(Icons.remove),
                            onPressed: () => context
                                .read(cartListPageStateNotifierProvider)
                                .removeProduct(item),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class CartListPageStateNotifier extends StateNotifier<CartListState> {
  final Reader reader;
  CartListPageStateNotifier(this.reader) : super(CartListState.initial());

  addProduct(CartListItemModel product) async {
    state = CartListState.loading();
    await Future.delayed(Duration(seconds: 1));
    var products = reader(cartListProvider).state;
    if (!products.contains(product)) {
      reader(cartListProvider).state.add(product);
      return state =
          CartListState.success("Added Successfully ${product.name}");
    } else {
      return state = CartListState.error(
          "cannot add more than 1 product of the same kind");
    }
  }

  removeProduct(CartListItemModel product) async {
    state = CartListState.loading();
    await Future.delayed(Duration(seconds: 1));
    var products = reader(cartListProvider).state;
    if (products.isNotEmpty) {
      bool status = reader(cartListProvider).state.remove(product);
      if (status) {
        return state =
            CartListState.success("removed Successfully ${product.name}");
      } else {
        return state;
      }
    }
    return state = CartListState.error("cart is empty");
  }
}

@freezed
abstract class CartListState with _$CartListState {
  const factory CartListState.initial() = _CartListInitial;
  const factory CartListState.loading() = _CartListLoading;
  const factory CartListState.success([String message]) = _CartListSuccess;
  const factory CartListState.error([String message]) = _CartListError;
}

@freezed
abstract class CartListItemModel with _$CartListItemModel {
  factory CartListItemModel({final String name, final int id}) =
      _CartListItemModel;
}

DON'T show snackbar here.不要在这里显示小吃店。 You need to listen to the needed value in the widget tree as the follows:您需要在小部件树中侦听所需的值,如下所示:

@override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.listen(cartListPageStateNotifierProvider, (value) {
      // show snackbar here...
    });
    ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用 StateNotifier Riverpod 来跟踪枚举值的变化 - How do i use StateNotifier riverpod to track the changes of enum value 如何使用 flutter riverpod statenotifier、ref watch 和 asyncvalue 获取加载状态/微调器? - How do I get loading state/spinner with flutter riverpod statenotifier, ref watch and asyncvalue? Riverpod:您如何使用 StateNotifier 管理加载和错误状态? - Riverpod: How do you manage loading and error states with StateNotifier? 如何从 Riverpod 中的另一个提供程序修改 StateNotifier 提供程序的 state? - How to modify the state of a StateNotifier Provider from another provider in Riverpod? 如何使用 Riverpod 的 statenotifier 处理表单? - How can I use riverpod's statenotifier for handling a form? Riverpod 在错误时显示 snackbar 以及使用 statenotifier 的最后已知列表 - Riverpod showing snackbar on Error and also last known list using statenotifier 带有 Riverpod 的 StateNotifier - StateNotifier with riverpod Flutter/Riverpod:从另一个StateNotifier调用StateNotifier中的方法 - Flutter/Riverpod: Call method within StateNotifier from another StateNotifier 在Flutter中,如何从平台调用处理程序显示SnackBar? - In Flutter, how do I show a SnackBar from a platform call handler? 我想初始化 state。 (RiverPod:StateNotifier) - I want to initialize the state. ( RiverPod : StateNotifier )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM