You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter页面切换后isAdded变量状态异常求助

解决Riverpod状态在页面返回后失效的问题

问题原因

  1. CartNotifier未初始化加载数据库数据:CartNotifier构造函数默认初始化空数组,没有从SQLite数据库加载已有的购物车数据。页面切换返回后,ref.watch(cartProvider)拿到的是初始空数组,导致isAdded错误显示为false。
  2. Coffee类未重写相等判断:List.contains()依赖对象的==运算符,默认==仅判断对象引用是否相同。从数据库加载的Coffee对象和页面传入的widget.coffee是不同实例,即使数据完全一致,contains()也会返回false。

解决方案

1. 在Provider初始化时加载数据库数据

修改cartProvider的创建逻辑,初始化CartNotifier后立即调用loadCoffee(),确保初始状态从数据库同步:

final cartProvider = StateNotifierProvider<CartNotifier, List<Coffee>>(
  (ref) {
    final notifier = CartNotifier();
    // 初始化时加载数据库中的购物车数据
    notifier.loadCoffee();
    return notifier;
  },
);

2. 重写Coffee类的==和hashCode

在Coffee模型类中添加相等判断逻辑,让contains()能根据数据内容识别相同对象:

class Coffee {
  final String id;
  final String coffeeImage;
  final String coffeeName;
  final double coffeePrice;

  Coffee({
    required this.id,
    required this.coffeeImage,
    required this.coffeeName,
    required this.coffeePrice,
  });

  // 重写==运算符,根据数据字段判断相等
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Coffee &&
          runtimeType == other.runtimeType &&
          id == other.id &&
          coffeeImage == other.coffeeImage &&
          coffeeName == other.coffeeName &&
          coffeePrice == other.coffeePrice;

  // 重写hashCode,配合==使用
  @override
  int get hashCode => Object.hash(id, coffeeImage, coffeeName, coffeePrice);
}

3. 规范removeCoffee方法的返回类型

removeCoffee内部使用了await,将返回类型改为Future<void>更符合异步操作规范:

Future<void> removeCoffee(Coffee coffee) async {
  final db = await _getDatabase();
  await db.delete(
    'cart_provider',
    where: 'id = ?',
    whereArgs: [coffee.id],
  );

  state = state.where((c) => c != coffee).toList();
}

验证效果

完成修改后,页面切换返回时:

  • cartProvider会从数据库加载最新购物车数据,ref.watch(cartProvider)能获取正确列表
  • isAdded = ref.watch(cartProvider).contains(widget.coffee)会根据数据内容正确判断状态,而非对象引用

内容的提问来源于stack exchange,提问作者Ehsan Javdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:55:02