如何在Flutter的build方法中使用ListView.builder和groupBy

d7v8vwbk  于 2023-05-19  发布在  Flutter
关注(0)|答案(2)|浏览(122)

我有一个这样的列表:

List<ProductModel> productList = [
    ProductModel(name: "Oranges", date: "2023-05-01"),    
    ProductModel(name: "Apples", date: "2023-05-01"),
    ProductModel(name: "Kiwis", date: "2023-03-01"),
];

我想使用groupBy按日期对项目进行分组,并将其显示在Widget build中:

2023-05-01:
Oranges
Apples

2023-03-01:
Kiwis

我已经在一个列表中完成了分组,当打印出来时,我的groupByDate列表看起来像这样:

{2023-05-01: [Instance of 'ProductModel', Instance of 'ProductModel'], 2023-03-01: [Instance of 'ProductModel']}

现在,问题是如何使用ListView.builder在build方法中显示列表项:

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

class _ProductListPageState extends State<ProductListPage> {
  late StreamController<int> _postsController;
  var groupByDate;

  @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);
      }    
      groupByDate = groupBy(productList, (obj) => (obj! as ProductModel).date);

    });
  }

  @override
    Widget build(BuildContext context) {            
      return Scaffold(
        body: ListView.builder(
            itemCount: groupByDate.length,
            itemBuilder: (context, index) {
              final key = groupByDate.keys.elementAt(index);
              final values = groupByDate.values.elementAt(index);
              return Column(
                children: [
                   Text("$key"),
                   Column(
                     children: [
                       //How do I show the list with values here??? 
                       entry.value.map((e) => Text(e.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,
  };
}
1qczuiv0

1qczuiv01#

你所要做的就是将groupByDate变量定义为Map。而不是仅仅

var groupByDate;

把那个改成

var groupByDate = <String, List<ProductModel>>{};

这样编译器就知道这是一个Map。

**编辑。**问题澄清后,以下是如何显示分组值列表

ListView.builder(
        itemCount: groupByDate.length,
        itemBuilder: (context, index) {
          final key = groupByDate.keys.elementAt(index);
          final values = groupByDate.values.elementAt(index);
          return Column(children: [
            Text("$key"),
            for (var item in values)
            Text("${item.name}"),
          ]);
        })
hvvq6cgz

hvvq6cgz2#

您需要使用groupByDate.entries来获取Map中的条目列表,这样您就可以访问keyvalue

@override
Widget build(BuildContext context) {
  return Scaffold(
      body: ListView.builder(
          itemCount: groupByDate.length,
          itemBuilder: (context, index) {
            final entry = groupByDate.entries.elementAt(index);
            return Column(children: [
              Text(entry.key ??
                  ''), 
              Column(
                children: entry.value.map((e) => Text(e.name ?? '')).toList(),
              )
            ]);
          }));
}

相关问题