1
0

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 1 year has passed since last update.

【flutter】addEntries

Posted at

はじめに

FutterのMapクラスは、値をキーとバリューのペアとして格納できる非常に便利なデータ構造です。このブログではMapに新しいエントリを追加するaddEntriesについて他のマップから全部追加する時, 単純に新しいkeyとvalueを追加したい時の2つの観点から紹介します。

他のマップから全部追加する時

一つのMapから別のMapに全てのエントリを追加する場合、addEntriesを用いて以下のように書くことができます。

コード

    final fruits = <int, String>{
      1: 'Apple',
      2: 'Banana',
      3: 'Cherry',
    };
    final gasGiants = <int, String>{4: 'Plum', 5: 'Grapes'};
    final iceGiants = <int, String>{6: 'Orange', 7: 'Peach'};
    print("✅ 変更前: $fruits");
    fruits.addEntries(gasGiants.entries);
    print("✅ 追加(1回目): $fruits");
    fruits.addEntries(iceGiants.entries);
    print("✅ 追加(2回目): $fruits");

結果

✅ 変更前: {1: Apple, 2: Banana, 3: Cherry}
✅ 追加(1回目): {1: Apple, 2: Banana, 3: Cherry, 4: Plum, 5: Grapes}
✅ 追加(2回目): {1: Apple, 2: Banana, 3: Cherry, 4: Plum, 5: Grapes, 6: Orange, 7: Peach}

単純に新しいkeyとvalueを追加したい時

単一のキーとバリューのペアをマップに追加する場合はMapEntryクラスを使用して以下のように書くことができます。

コード

    final fruits_2 = {
      1: 'Apple',
      2: 'Banana',
      3: 'Cherry',
    };
    print("✅ 変更前: $fruits_2");
    fruits_2.addEntries([
      MapEntry(4, 'Plum'),
      MapEntry(3, 'Grapes'),
    ]);
    print("✅ 更新, 追加後: $fruits_2");

結果

✅ 変更前: {1: Apple, 2: Banana, 3: Cherry}
✅ 更新, 追加後: {1: Apple, 2: Banana, 3: Grapes, 4: Plum}

コード全文

参考

他のマップから全部追加する時

単純に新しいkeyとvalueを追加したい時

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?