flutter中,有一个集合,改变集合对象的某一个属性?

有一个List<Goods>,Goods只有两个属性,一个isCollection表示是否收藏,一个goodsName表示名称。

业务场景是,前端有一个List<Goods>是配置好的,只是商品的isCollection是否收藏需要通过后端接口返回,我在initState()里面调用api接口,在接口中修改某一行的isCollection但是页面没有刷新,请问怎么回事?

阅读 586
1 个回答

在 Flutter 里,若要改变集合对象的某个属性,并且让界面刷新以反映这些更改,就需要借助 Flutter 的状态管理机制。界面不刷新往往是因为没有正确触发状态更新。下面详细分析你的问题并给出解决方案。
在 Flutter 中,修改 List<Goods> 里某个 Goods 对象的 isCollection 属性时,界面不会自动刷新。这是因为 Flutter 不会自动检测到集合内部对象属性的变化。你得调用 setState 方法来通知 Flutter 状态已经改变,从而触发界面刷新。

以下是一个完整的示例代码,展示了如何在 initState 中调用模拟的 API 接口,更新 List<Goods> 中每个 Goods 对象的 isCollection 属性,并且让界面刷新:

import 'package:flutter/material.dart';

// 定义 Goods 类
class Goods {
  bool isCollection;
  String goodsName;

  Goods({required this.isCollection, required this.goodsName});
}

class GoodsListPage extends StatefulWidget {
  @override
  _GoodsListPageState createState() => _GoodsListPageState();
}

class _GoodsListPageState extends State<GoodsListPage> {
  List<Goods> goodsList = [
    Goods(isCollection: false, goodsName: '商品1'),
    Goods(isCollection: false, goodsName: '商品2'),
    Goods(isCollection: false, goodsName: '商品3'),
  ];

  @override
  void initState() {
    super.initState();
    // 模拟调用 API 接口
    fetchCollectionStatus();
  }

  // 模拟 API 接口调用
  Future<void> fetchCollectionStatus() async {
    // 模拟网络延迟
    await Future.delayed(Duration(seconds: 2));

    // 模拟从后端获取的收藏状态
    List<bool> collectionStatus = [true, false, true];

    setState(() {
      for (int i = 0; i < goodsList.length; i++) {
        goodsList[i].isCollection = collectionStatus[i];
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品列表'),
      ),
      body: ListView.builder(
        itemCount: goodsList.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(goodsList[index].goodsName),
            trailing: Icon(
              goodsList[index].isCollection
                  ? Icons.favorite
                  : Icons.favorite_border,
              color: goodsList[index].isCollection ? Colors.red : null,
            ),
          );
        },
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: GoodsListPage(),
  ));
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题