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

Flutter修改List<Map<String, dynamic>>数据后UI未即时更新问题求助

问题原因
  • 数据未持久化存储:你当前使用的amount字段是每次调用listData方法时,在局部生成的products列表中初始化的临时值,默认强制为0,修改后没有同步到全局的ProductNotifier状态中。
  • 修改后未触发UI刷新:你更新products内的数值后,既没有调用setState触发当前Widget重绘,也没有调用ProductNotifier的notifyListeners()方法通知状态监听者更新UI。
  • 折叠展开才更新的原因:ExpansionTile折叠时会销毁内部子控件,重新展开时会重新执行listData方法重建子视图,此时你之前修改的临时值才会被加载到新生成的控件上。
解决方案
  1. 首先在你的Product实体类中新增amount字段,初始值设为0,把商品数量直接存储在全局ProductNotifier的productList中,不要每次临时生成。
class Product {
  String name;
  String category;
  // 新增数量字段
  int amount = 0;
  Product({required this.name, required this.category});
}
  1. 修改listData方法逻辑,修改数据后通知状态刷新,同时用Consumer包裹需要刷新的区域,避免不必要的全局重绘:
Widget listData(String category) {
  // 这里listen设为false,避免整个列表频繁重绘
  ProductNotifier productNotifier = Provider.of<ProductNotifier>(context, listen: false);
  // 直接过滤全局状态中的商品,不生成新的临时Map
  List<Product> products = productNotifier.productList.where((p) => p.category == category).toList();

  return ListView.separated(
    shrinkWrap: true,
    physics: NeverScrollableScrollPhysics(),
    itemCount: products.length,
    separatorBuilder: (_, __) => SizedBox(height: 5),
    itemBuilder: (context, index) {
      // 仅包裹需要更新的商品条目
      return Consumer<ProductNotifier>(
        builder: (_, notifier, __) {
          final currentProduct = products[index];
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  currentProduct.name,
                  style: FontCollection.bodyBlackTextStyle,
                ),
                CustomStepper(
                  value: currentProduct.amount,
                  iconSize: 25,
                  increaseAmount: () {
                    // 直接修改全局状态中的商品数量
                    currentProduct.amount += 1;
                    // 通知监听者刷新UI
                    notifier.notifyListeners();
                  },
                )
              ],
            ),
          );
        }
      );
    },
  );
}
  1. 移除CustomStepper上不必要的UniqueKey,避免控件无意义重建导致的性能损耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:54:05