1

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 !

1 Answer 1

2

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();
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.