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

huangapple go评论65阅读模式
英文:

How to use ListView.builder with groupBy in build method in Flutter

问题

以下是您要翻译的代码部分:

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

2023-05-01:
Oranges
Apples

2023-03-01:
Kiwis

...

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(),
                    ])
            ])
    }
)

请注意,我已经删除了注释部分并翻译了代码。如果您需要进一步的帮助或有其他问题,请告诉我。

英文:

I have a list like this:

List&lt;ProductModel&gt; productList = [
    ProductModel(name: &quot;Oranges&quot;, date: &quot;2023-05-01&quot;),    
    ProductModel(name: &quot;Apples&quot;, date: &quot;2023-05-01&quot;),
    ProductModel(name: &quot;Kiwis&quot;, date: &quot;2023-03-01&quot;),
];

I would like to group the items by date using groupBy and display it in Widget build as so:

2023-05-01:
Oranges
Apples

2023-03-01:
Kiwis

I have already done the grouping in a list and when printed my groupByDate list looks like so:

{2023-05-01: [Instance of &#39;ProductModel&#39;, Instance of &#39;ProductModel&#39;], 2023-03-01: [Instance of &#39;ProductModel&#39;]}

Now, the question is how do I use ListView.builder to display the list items in build method:

class ProductListPage extends StatefulWidget {
  @override
  State&lt;StatefulWidget&gt; createState() =&gt; new _ProductListPageState();
}

class _ProductListPageState extends State&lt;ProductListPage&gt; {
  late StreamController&lt;int&gt; _postsController;
  var groupByDate;

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

  void getProducts() {
    Fetch.getProdcuts().then((value) =&gt; {
      _postsController.add(1);
      
      List&lt;ProductModel&gt; 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) =&gt; (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(&quot;$key&quot;),
                   Column(
                     children: [
                       //How do I show the list with values here??? 
                       entry.value.map((e) =&gt; Text(e.name)).toList(),
                   ])
              ])
            }
        )
      );
    }

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

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

  ProductModel.fromJson(Map&lt;String, dynamic&gt; json) {
    name = json[&quot;name&quot;];
    date = json[&quot;date&quot;];
  }

  Map&lt;String, dynamic&gt; toJson() =&gt; {
    &#39;name&#39;: name,
    &#39;date&#39;: date,
  };
}

答案1

得分: 1

Sure, here's the translated code portion:

你只需将groupByDate变量定义为Map。不要只是:

var groupByDate;

改成:

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

这样编译器就会知道它是一个映射。

编辑。 根据问题的澄清,以下是如何显示分组值的列表:

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}"),
    ]);
  }
)
英文:

All you have to do is define your groupByDate variable as Map. Instead of just

var groupByDate;

change that to

var groupByDate = &lt;String, List&lt;ProductModel&gt;&gt;{};

so the compiler would know it's a map.

Edit. Upon question clarification, here's how you show the list of grouped values

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

答案2

得分: 1

你需要使用 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(),
              )
            ]);
          }));
}
英文:

You need to use groupByDate.entries to get a list of entries in a Map, that way you will have access to both key & value:

@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 ??
                  &#39;&#39;), 
              Column(
                children: entry.value.map((e) =&gt; Text(e.name ?? &#39;&#39;)).toList(),
              )
            ]);
          }));
}

huangapple
  • 本文由 发表于 2023年5月11日 19:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定