有没有一种快速的方法可以从现有对象创建 Dart 类的新实例?

时间:2021-06-10 10:20:56

标签: flutter dart

基本上想知道除了创建一个从自身创建新类实例的方法之外是否还有其他快速方法,因此下面的示例将打印 9,而不是 15。

void main() {
  
  final classOne = SomeClass(mutableString: 'Hello', mutableInt: 9); 
  
  final classTwo = classOne; 
  
  classTwo.mutableInt = 15; 
  
  print(classOne.mutableInt); 
  
}


class SomeClass {
  
  SomeClass({required this.mutableString, required this.mutableInt}); 
  
  String mutableString; 
  int mutableInt; 
}

谢谢

2 个答案:

答案 0 :(得分:1)

您可以在类中添加一个返回相同对象的方法。 例如 : 我在 SomeClass 中添加 copyWith 方法


class SomeClass {
  SomeClass({required this.mutableString, required this.mutableInt});

  String mutableString;
  int mutableInt;

  SomeClass copyWith({int? mutableInt}) {
    return SomeClass(
      mutableString: this.mutableString,
      mutableInt: mutableInt ?? this.mutableInt,
    );
  }
}

现在您可以使用该方法:

void main() {
  
  final classOne = SomeClass(mutableString: 'Hello', mutableInt: 9); 
  
  final classTwo = classOne.copyWith(mutableInt:15);; 
  
  print(classOne.mutableInt); 
  
}

答案 1 :(得分:1)

@anoncgain 解决方案在一定程度上是正确的。

你也可以这样做


class SomeClass {
  //...other code ....
  String? mutableString; //make your params nullable
  int? mutableInt; 
  
  //declare a named constructor to copp the existing object value.
  SomeClass.copy(SomeClass object){
    mutableString = object.mutableString;
    mutableInt = object.mutableInt;
  }
}

然后你可以把它当作

final classTwo = SomeClass.copy(classOne);
//it will copy the values to the newly created object 
//rather then storing the reference of the object
相关问题