簡體   English   中英

Flutter Dart | 如何從 class 構造函數返回不同的 object

[英]Flutter Dart | How to return different object from class Constructor

Dart中, constructor是否可以取消 object 創建並返回不同的 object ?

用例: Users包含一個 static map 將 id 映射到User對象。 初始化User時,我希望User constructor檢查是否已創建具有idUser ,如果是:返回現有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;
 }
}

問題:有沒有辦法讓上面的偽代碼工作?

正如jamesdlin所提到的,您應該使用工廠構造函數。 這是文檔中提到的內容

在實現並不總是創建其類的新實例的構造函數時使用 factory 關鍵字。

在您的情況下,這正是您想要的。 現在這是一個代碼示例,可以執行您想要的操作:

代碼示例

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;
  }
}

在 DartPad 上嘗試完整代碼

你可以在類中創建一個函數來處理你想要的東西。 這是您可以實施的。

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

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

如果這是出於緩存目的,或者您沒有創建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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM