flutter 如何在Dart中修改模型?

zour9fqk  于 2023-06-30  发布在  Flutter
关注(0)|答案(2)|浏览(144)

我尝试修改一个对象:

void main() {
  
  Model item = Model(list: [3,4]);
  print(item.list);
  Model test = item;
  List modifyList = test.list!;
  modifyList[0] = 999;
  test = Model(list: modifyList);
  print("original: " + item.list.toString());
  print("modified: " + test.list.toString());
  
}
  
  class Model {
  String? title;
  String? postid;
  List? list;

  Model({
    this.title,
    this.postid,
    this.list,
  });
    
    
}

这将打印:

[3, 4]
original: [999, 4]
modified: [999, 4]

我不明白为什么原始测试模型的第一个参数也被修改了。如何仅修改测试模型并保留原始模型?
为什么要修改原来的变量,即使我以前已经把它放在新的测试?

weylhg0b

weylhg0b1#

你不能这样做,因为它引用了原始对象
尝试深拷贝更改值

Model item = Model(list: [3,4]);
  print(item.list);
  Model test = item.copyWith(list: [999,item.list![1]]);
  print("original: " + item.list.toString());
  print("modified: " + test.list.toString());
  
}
  
  class Model {
  String? title;
  String? postid;
  List? list;

  Model({
    this.title,
    this.postid,
    this.list,
  });
  /// Add copyWith to mutate an the original object
  Model copyWith({
    String? title,
  String? postid,
  List? list,
  }) {
    return Model(title: title??this.title, postid:postid??this.postid, list:list ??this.list);
  }
}

输出:

[3, 4]
original: [3, 4]
modified: [999, 4]
7lrncoxx

7lrncoxx2#

我最后修改了@Jason的copyWith,并添加了List.from来克隆列表并删除引用:

void main() {
  
  Model item = Model(list: [3,4]);
  print(item.list);
  
  List modifyList = List.from(item.list!);
  modifyList[0] = 999;
  
  Model test = item.copyWith(list: modifyList);

  print("original: " + item.list.toString());
  print("modified: " + test.list.toString());
  
}
  
  class Model {
  String? title;
  String? postid;
  List? list;

  Model({
    this.title,
    this.postid,
    this.list,
  });
    
   Model copyWith(
      {String? title,
      String? postid,
      List? list,
      }) {
    return Model(
        title: title ?? this.title,
        
        postid: postid ?? this.postid,
      
        list: list ?? this.list,
       );
  }
    
 
    
    
}

输出:

[3, 4]
original: [3, 4]
modified: [999, 4]

没有引用的克隆列表:https://stackoverflow.com/a/71031170/3037763
另一种方式是.toList()https://stackoverflow.com/a/62013491/3037763

相关问题