1. string type
main(List<String> args) {
String name = "huhx";
changIt(name);
print('after: $name'); // after: huhx
}
void changIt(String name) {
print('before: $name'); // before: huhx
name = "linux";
}
2. reference Type
class User {
String name;
User(this.name);
}
main(List<String> args) {
User user = User("huhx");
changIt(user);
print('after: ${user.name}'); // after: linux
}
void changIt(User user) {
print('before: ${user.name}'); // before: huhx
user.name = "linux";
}
3. deep clone
import 'dart:convert';
class User {
String name;
User(this.name);
factory User.fromJson(Map<String, dynamic> userMap) => User(userMap['name']);
Map<String, dynamic> toJson() => {'name': this.name};
User clone() {
final String jsonString = json.encode(this);
final jsonResponse = json.decode(jsonString);
return User.fromJson(jsonResponse as Map<String, dynamic>);
}
}
main(List<String> args) {
User user = User("huhx");
changIt(user);
print('after: ${user.name}'); // after: huhx
}
void changIt(User user) {
User temp = user.clone();
// User temp = user; then: after linux
print('before: ${temp.name}'); // before: huhx
temp.name = "linux";
}
|
请发表评论