Flutter中Riverpod+sqflite防重复添加商品逻辑失效求助
问题根源
你当前的防重复逻辑失效,核心原因是Dart默认的对象相等性判断基于引用而非属性。即使两个Coffee实例的id等属性完全一致,只要它们是不同对象(比如从数据库读取的实例、或每次点击时传递的新创建实例),state.contains(coffee)就会返回false,导致重复添加。
解决方案
以下两种修复方式任选其一即可:
方案1:重写Coffee类的==运算符和hashCode
让Coffee类根据唯一标识(比如id)判断相等性,这样contains方法就能正确识别重复商品:
class Coffee { final String id; // 假设id是商品唯一标识 final String coffeeImage; final String coffeeName; final double coffeePrice; Coffee({ required this.id, required this.coffeeImage, required this.coffeeName, required this.coffeePrice, }); // 基于id判断对象相等 @override bool operator ==(Object other) => identical(this, other) || other is Coffee && runtimeType == other.runtimeType && id == other.id; // 基于id生成hashCode @override int get hashCode => id.hashCode; }
方案2:修改addCoffee方法的判断逻辑
不依赖contains,直接通过id检查state中是否已存在该商品:
void addCoffee(Coffee coffee) async { // 通过id判断商品是否已存在 final exists = state.any((item) => item.id == coffee.id); if (exists) { return; } else { final db = await _getDatabase(); await db.insert( 'cart_provider', { 'id': coffee.id, 'coffeeImage': coffee.coffeeImage, 'CoffeeName': coffee.coffeeName, 'CoffeePrice': coffee.coffeePrice, }, ); state = [...state, coffee]; } }
额外调试建议
可以在addCoffee方法中加入日志,打印当前state中所有商品的id和当前要添加的coffee.id,方便快速验证判断逻辑是否生效:
void addCoffee(Coffee coffee) async { print('Current cart ids: ${state.map((c) => c.id).join(', ')}'); print('Adding coffee id: ${coffee.id}'); // ... 原有逻辑 }
内容的提问来源于stack exchange,提问作者Ehsan Javdan
相关产品推荐
相关产品推荐

