0
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】ListをListにaddしたあとclearするとadd先のリストも消える

Posted at

以下の例では、最終的にlist2に追加したlist1が消えてしまうようです。

sample.dart

    List data1 = [なんらかのリスト];
    List<クラス1> list1 = [];
    List<クラス2> list2 = []; //クラス1を引数とするコンストラクタを持つ

    for (var i = 0; i < data1.length; i++) {
      list1.clear(); //ループごとに初期化

      if(data1[i]==なんらかの条件) {
          list1.add(データ);
      }
      list2.add(クラス2(list1));
    }

 
 
 

これを防ぐには、リストの初期化部分で
.clearメソッドではなく**[]で空白リスト**を代入するようにします。

sample.dart

    List data1 = [なんらかのリスト];
    List<クラス1> list1 = [];
    List<クラス2> list2 = []; //クラス1を引数とするコンストラクタを持つ

    for (var i = 0; i < data1.length; i++) {
      list1 = []; //ループごとに初期化

      if(data1[i]==なんらかの条件) {
          list1.add(データ);
      }
      list2.add(クラス2(list1));
    }


0
1
1

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