Flutter Dart | How to return different object from class Constructor
As mentioned by 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.
And in your case this is exactly what you want. Now here's a code sample that does what you want:
Code sample
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;
}
}
Vingtoft
Updated on December 06, 2022Comments
-
Vingtoft over 1 year
In
Dart
, is it possible for aconstructor
to cancel object creation and return a different object instead?Use case:
Users
contains a static map that maps ids toUser
objects. When aUser
is initialized, I want theUser
constructor
to check ifUser
withid
is already created, if so: return existingUser object
, else create a newUser object
Example (of-course not working):
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; } }
Question: IS there any way to get the above pseudo code to work?