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

【Dart】Listのディープコピー

Posted at

DartのListにはcloneメソッドがないので、ディープコピーするには、

final test = [1, 2, 3];
final test2 = [...test];

と書く。

しかし、この書き方は、リスト内の要素がプリミティブな型(数値、文字列など)である場合にのみ機能する。

リストの要素が参照型(クラスとか)の場合は、要素もディープコピーする必要がある。

class Dog {
  Dog({required this.name});

  String name;

  @override
  String toString() {
    return '{name=$name}';
  }

  // クローン用メソッドを用意する
  Dog clone({String? name}) {
    return Dog(name: name ?? this.name);
  }
}

=====

// コピーの書き方

final dogList = <Dog>[Dog(name: 'Pochi'), Dog(name: 'Kuro'), Dog(name: 'Waaan')];
final copyList = [...dogList]; // ダメ
final copyList2 = dogList.map((item) => item.clone()).toList(); // OK

環境

Flutter 3.7.12 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 4d9e56e694 (3 months ago) • 2023-04-17 21:47:46 -0400
Engine • revision 1a65d409c7
Tools • Dart 2.19.6 • DevTools 2.20.1

参考

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