1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Dart/FlutterでGroup By

Last updated at Posted at 2021-10-02

groupListsBy

ListをあるKeyでGroup化するにはgroupListsByが使えます。

環境

Dart SDK version: 2.14.2 (stable) (Wed Sep 15 12:32:06 2021 +0200) on "windows_x64"

実装

import "package:collection/collection.dart";

void main(List<String> args) {
  var list = [
    {'groupId': 1, 'label': 'レタス'},
    {'groupId': 2, 'label': 'カルビ'},
    {'groupId': 1, 'label': 'しいたけ'},
    {'groupId': 3, 'label': 'レモン'},
    {'groupId': 2, 'label': 'ロース'},
  ];

  print('original list:');
  list.asMap().forEach((key, value) => print("$key: $value"));

  print('\x0Agrouped list:');
  var listByGroupId = list.groupListsBy((obj) => obj['groupId']);
  listByGroupId.forEach((key, value) => print("$key: $value"));
}

実行結果

original list:
0: {groupId: 1, label: レタス}
1: {groupId: 2, label: カルビ}
2: {groupId: 1, label: しいたけ}
3: {groupId: 3, label: レモン}
4: {groupId: 2, label: ロース}

grouped list:
1: [{groupId: 1, label: レタス}, {groupId: 1, label: しいたけ}]
2: [{groupId: 2, label: カルビ}, {groupId: 2, label: ロース}]  
3: [{groupId: 3, label: レモン}]

補足

当初groupByを使おうとして以下を試したのですが構文エラーになりました。

groupBy(list, (obj) => obj['groupId']);

エラー

The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!').dartunchecked_use_of_nullable_value

以上

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?