社区首页 >问答首页 >如何在Riverpod中显示StateNotifier中的快餐栏?

如何在Riverpod中显示StateNotifier中的快餐栏?
EN

Stack Overflow用户
提问于 2021-02-22 14:01:50
回答 2查看 381关注 0票数 0

我有下面的类,它工作得很好。

代码语言:javascript
代码运行次数:0
复制
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();
    }
  }

上面的代码运行得很好。在我的购物车中,我希望将产品的订单限制为1个单位,这就是为什么我要执行上面的代码。它和我预期的一样工作。现在唯一的事情是,我想显示一个快餐栏,提醒用户他或她只能订购每个产品的1个单位。

如何在我的StateNotifier中添加一个快餐栏?

EN

回答 2

Stack Overflow用户

发布于 2021-03-03 00:39:40

代码语言:javascript
代码运行次数:0
复制
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;
}
票数 2
EN

Stack Overflow用户

发布于 2021-10-17 22:12:28

不要在这里显示小吃店。您需要监听小部件树中所需的值,如下所示:

代码语言:javascript
代码运行次数:0
复制
@override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.listen(cartListPageStateNotifierProvider, (value) {
      // show snackbar here...
    });
    ...
  }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66317145

复制
相关文章
eclipse使用svn更新代码_eclipse安装svn
1.先去将本地的代码更新到最新,如果更新内容较少,可以点击资源同步,具体可以看一下博主: svn创建 svn图文 2.更新成最新的代码之后,点击创建补丁,点击第二个file 文本框,选择一个文件夹存下一个文件。 3.打开申请上线权限,。点击puth,填写./ 4.申请通过之后,复制review + 版本号 5.将复制的版本号放到comment下 6.点击ok 。
全栈程序员站长
2022/11/01
1.9K0
eclipse如何使用svn_eclipse使用svn提交代码步骤
eclipse对svn的支持力度较小,在比较高的版本中也没有集成svn的插件,对git的支持还是不错的,如果想要学习git的同学可以学习我博客中关于git的学习笔记 git使用教程,非常详细
全栈程序员站长
2022/11/10
2K0
eclipse如何使用svn_eclipse使用svn提交代码步骤
eclipse SVN插件_eclipse安装svn
利用中文插件,我们可以更加直观的理解Eclipse SVN 的功能 ,下面为配置具体步骤:
全栈程序员站长
2022/11/04
2.2K0
eclipse配置svn的步骤_eclipse切换svn地址
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/09
1.2K0
eclipse配置svn的步骤_eclipse切换svn地址
Eclipse中使用SVN Eclipse配置SVN[通俗易懂]
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/10
4.7K0
Eclipse中使用SVN Eclipse配置SVN[通俗易懂]
eclipse的svn切换账号_eclipse将项目和svn关联
百度搜了下全都是不知道哪年的一篇博客被疯狂转载,删除缓存文件的。但是根本不顶用。直接上我的解决方案吧(来自stackoverflow)。
全栈程序员站长
2022/11/04
9710
如何在js中将统计代码图标隐藏
  建站时我们都会加一下网站统计,方便把控内容的内容的运营。大部分站长安装的站点统计是第三方统计代码,js形式的,很少用以服务器日志为基础分析的统计。(当然能通过网站日志来分析网站的运营者比一般的站长水平相对要高一些,也更会折腾。因为很多统计都没记录蜘蛛的轨迹)普通的js统计代码就能满足大多数的需求。安装统计代码想必大家闭着眼睛都会,但如果网站是静态页面的话,那每个页面都要添加到,即使安装在统一调用的页脚,那生成页面也需要一定的时间。有没更便捷的办法呢?将统计代码写进常用的js文件中。   将统计代码写进j
ytkah
2018/03/05
13.4K0
如何在js中将统计代码图标隐藏
eclipse中通过svn检出项目代码
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/105816.html原文链接:https://javaforall.cn
全栈程序员站长
2022/08/09
2630
eclipse中通过svn检出项目代码
eclipse中向svn提交代码冲突的解决
1. 点击提交,报错——‘SVN提交’has encountered a problem.
小小鱼儿小小林
2020/06/23
1.1K0
eclipse svn上传代码_svn统计每个人代码提交行数
1.先去将本地的代码更新到最新,如果更新内容较少,可以点击资源同步,具体可以看一下博主: svn创建 svn图文 2.更新成最新的代码之后,点击创建补丁,点击第二个file 文本框,选择一个文件夹存下一个文件。 3.打开申请上线权限,。点击puth,填写./ 4.申请通过之后,复制review + 版本号 5.将复制的版本号放到comment下 6.点击ok 。
全栈程序员站长
2022/11/04
6860
eclipse配置svn的步骤_如何访问svn地址
所有的WEB访问都变成HTTPS,例如,localhost将无法访问,需要访问https://localhost,这个应该是可以在https.conf文件中配置区分的,暂时不做处理,故建议此服务器不再当作WEB服务器。
全栈程序员站长
2022/10/03
1.4K0
eclipse离线安装svn插件使用教程_eclipse导入svn项目
结果:失败,下载失败,换一个版本的插件安装成功,但连接仓库会提示0x00400006
全栈程序员站长
2022/11/04
3.2K0
eclipse从svn下载项目_eclipse配置
file –> import —> svn —-> 输入svn地址 导出为Java项目
全栈程序员站长
2022/11/08
1.4K0
Eclipse安装SVN插件
SVN插件下载地址及更新地址,你根据需要选择你需要的版本。现在最新是1.8.x Links for 1.8.x Release: Eclipse update site URL: http:/
似水的流年
2018/01/18
1.3K0
Eclipse安装SVN插件
新版eclipse自动补全代码不能用怎么办_eclipse打开代码提示
最新下了新版的eclipse,版本为4.4 和 4.2, 发现这两个版本都无法自动补全代码,经过与原来eclipse比较,发现有几项key的设置有问题,现在分享出来,以供和我遇到一样问题的人参考。设置如下:
全栈程序员站长
2022/11/04
1.4K0
新版eclipse自动补全代码不能用怎么办_eclipse打开代码提示
eclipse离线安装svn插件使用教程_eclipse不显示svn插件
昨天心血来潮,因为总是有些小的测试文档修改了修改去,后来某天找代码又麻烦得很,想把本机上的所有代码管理起来,在网上度娘了下,决定在Eclipse中安装svn插件,来管理本地的源代码文档。现在附上一些安装步骤,后续的使用慢慢地摸索吧。
全栈程序员站长
2022/11/10
1.1K0
eclipse离线安装svn插件使用教程_eclipse不显示svn插件
eclipse SVN插件的缓存清理[通俗易懂]
情况一:eclipse清理网页缓存。修改了代码多次刷新页面[已经清除过浏览器缓存]后页面调试仍显示源代码
全栈程序员站长
2022/11/04
1.9K0
eclipse J2EE中将servlet与freemarker结合使用
我参考:http://314858770.iteye.com/blog/966863 
克虏伯
2019/04/15
6500
eclipse J2EE中将servlet与freemarker结合使用
Eclipse安装SVN插件
SVN插件下载地址及更新地址,你根据需要选择你需要的版本。现在最新是1.8.x Links for 1.8.x Release: Eclipse update site URL: http://sub
似水的流年
2019/12/13
6480
Eclipse安装SVN插件
Eclipse安装SVN插件
SVN插件下载地址及更新地址,你根据需要选择你需要的版本。现在最新是1.8.x Links for 1.8.x Release: Eclipse update site URL: http://s
似水的流年
2018/01/12
9400

相似问题

如何通过另一个类访问方法并创建对象

13

通过对象访问类方法

21

如何通过不同的类访问对象方法?

42

C#如何通过父类的对象访问嵌套类的方法?

18

无法通过代理对象访问类方法

13
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文