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

Flutter使用groupBy按日期分组报错:运算符'[]'未定义于Object类型

解决Flutter中groupBy分组ProductModel的类型错误问题

问题根源

你遇到的The operator '[]' isn't defined for the type 'Object'和The getter 'date' isn't defined for the type 'Object'错误,本质是Dart的类型推断未识别出groupBy回调参数的具体类型,将其默认推断为Object,导致无法访问ProductModel的date属性。

核心解决方案

给groupBy的第二个回调参数明确指定ProductModel类型,同时处理date可能为null的情况:

// 修正后的分组代码
var groupByDate = groupBy(productList, (ProductModel obj) => obj.date?.substring(0, 10));

完整修正后的代码示例

class ProductListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  late StreamController<int> _postsController;
  // 新增变量存储分组后的数据,用于build中展示
  Map<String?, List<ProductModel>>? groupedProducts;

  @override
  void initState() {
    _postsController = new StreamController();
    getProducts();
    super.initState();
  }

  void getProducts() {
    Fetch.getProdcuts().then((value) {
      _postsController.add(1);
      
      List<ProductModel> productList = [];

      for (var item in value!) {
         final encode = json.encode(item.toJson());
         final product = ProductModel.fromJson(jsonDecode(encode));
         productList.add(product);
      }

      // 修正后的分组代码
      groupedProducts = groupBy(productList, (ProductModel obj) => obj.date?.substring(0, 10));
      // 通知UI更新
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Products")),
      body: groupedProducts == null 
          ? const Center(child: CircularProgressIndicator())
          : ListView(
              children: groupedProducts!.entries.map((entry) {
                final date = entry.key;
                final products = entry.value;
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        date ?? "无日期",
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                    ...products.map((product) => ListTile(
                      title: Text(product.name ?? "未知名称"),
                    )),
                  ],
                );
              }).toList(),
            ),
    );
  }
}

class ProductModel extends Object {
  String? name;
  String? date;

  ProductModel({this.name, this.date});

  ProductModel.fromJson(Map<String, dynamic> json) {
    name = json["name"];
    date = json["date"];
  }

  Map<String, dynamic> toJson() => {
    'name': name,
    'date': date,
  };
}

对之前尝试写法的错误分析

  • 尝试写法1:groupBy的第二个参数需要是一个返回分组键的函数,但你传了一个List<ProductModel>,参数类型完全不匹配,导致报错。
  • 尝试写法2:value!.toList()的元素类型是Object,所以回调里的obj是Object类型,没有date属性;另外obj?.date.substring(0,10).toList()是错误写法,substring返回字符串,不存在toList()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:17:45