飞镖 |如何 return 来自 class 构造函数的不同对象

Flutter Dart | How to return different object from class Constructor

Dart 中,是否可以 constructor 取消对象创建并 return 另一个对象?

用例: Users 包含一个将 id 映射到 User 对象的静态映射。 初始化 User 时,我希望 User constructor 检查是否已创建 Userid,如果是: return existing User object,否则创建一个新的 User object

示例(当然不起作用):

class Users {
  static const Map<String, User> users = {};
}

class User {
 final String id;
 final String firstName;

 User({required id, required firstName}) {
  // If user with id already exists, return that object
  if (Users.users.containsKey(id) {
    return Users.users[id];
  }
 // Else, initialize object and save it in Users.users
  this.id = id; 
  this.firstName = firstName;
  Users.users[id] = this;
 }
}

问题:有没有办法让上面的伪代码生效?

您可以在 class 中创建一个函数来处理您想要的事情。以下是您可以实施的内容。

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

  Player.fromPlayer(Player another) :
    color = another.color,
    name = another.name;
}

jamesdlin you should use a factory constructor. Here's what is mentioned in the documentation所述:

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class.

在您的情况下,这正是您想要的。现在这里有一个代码示例,可以满足您的需求:

代码示例

class Users {
  // Also your Map cannot be const if you want to edit it.
  static Map<String, User> users = {};
}

class User {
  final String id;
  final String firstName;

  /// Base private constructor required to create the User object.
  User._({required this.id, required this.firstName});

  /// Factory used to create a new User if the id is available otherwise return the User
  /// associated with the id.
  factory User({required String id, required String firstName}) {
    // If user with id already exists, return that object
    if (Users.users.containsKey(id)) {
      // Force casting as non nullable as we already checked that the key exists
      return Users.users[id]!;
    }
    
    // Else, initialize object and save it in Users.users
    final newUser = User._(id: id, firstName: firstName);
    Users.users[id] = newUser;
    return newUser;
  }
}

Try the full code on DartPad

如果这是出于缓存目的,或者您没有创建 Users class 的多个实例,我建议使用 static 负责 class 实例。有时这有助于显着减少代码量:

class User {
  static final Map<String, User> users = {};
  
  final String id, firstName;

  User._({required this.id, required this.firstName});
  
  factory User({required String id, required String firstName}) => users[id] ??= User._(id: id, firstName: firstName);
}