I want to create a model user like this:
@JsonSerializable()
class User {
final String id;
final String email;
final bool isAdmin;
final bool canDeleteUser;
final bool canCreateUser;
final String nom;
final String prenom;
final DateTime createdDate;
final DateTime modifiedDate;
User({
this.id = '',
this.email = '',
this.isAdmin = false,
this.nom = '',
this.prenom = '',
this.canCreateUser = false,
this.canDeleteUser = false,
this.createdDate = DateTime.now(),
this.modifiedDate = const DateTime.now(),
});
factory User.fromJson(Map<String, dynamic> json) => _$UsersFromJson(json);
Map<String, dynamic> toJson() => _$UsersToJson(this);
}
Fields createdDate and modifiedDate can't be initialize with DateTime.now(), I got this error message : The default value of an optional parameter must be constant.
If someone can tell me how can I use Datetime.now() has a default value, thanks !
CodePudding user response:
You should define the parameters after the {}
like so:
User({
this.id = '',
this.email = '',
this.isAdmin = false,
this.nom = '',
this.prenom = '',
this.canCreateUser = false,
this.canDeleteUser = false,
}) : createdDate = DateTime.now(),
modifiedDate = DateTime.now();
Full example:
class User {
final String id;
final String email;
final bool isAdmin;
final bool canDeleteUser;
final bool canCreateUser;
final String nom;
final String prenom;
final DateTime createdDate;
final DateTime modifiedDate;
User({
this.id = '',
this.email = '',
this.isAdmin = false,
this.nom = '',
this.prenom = '',
this.canCreateUser = false,
this.canDeleteUser = false,
}) : createdDate = DateTime.now(),
modifiedDate = DateTime.now();
}