Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

dart - Constructor Optional Params

Is there a way to set a constructor optional param? I mean something like:

User.fromData(this._name, 
  this._email, 
  this._token, 
  this._refreshToken,  
  this._createdAt,  
  this._expiresAt,  
  this._isValid,  
  {this.id});

It indicates that

Named option parameters can't start with an underscore.

But I need this field as private, so, I'm lost now.

question from:https://stackoverflow.com/questions/52449508/constructor-optional-params

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a more general answer for future viewers.

Positional optional parameters

Wrap the optional parameter with [ ] square brackets.

class User {

  String name;
  int age;
  String home;

  User(this.name, this.age, [this.home = 'Earth']);
}

User user1 = User('Bob', 34);
User user2 = User('Bob', 34, 'Mars');

Optional parameters need to be nullable if you don't provide a default value:

class User {

  String name;
  int age;
  String? home; //    <-- Nullable

  User(this.name, this.age, [this.home]);
}

Named optional parameters

Wrap the optional parameter with { } curly braces.

class User {

  String name;
  int age;
  String home;

  User(this.name, this.age, {this.home = 'Earth'});
}

User user1 = User('Bob', 34);
User user2 = User('Bob', 34, home: 'Mars');

The default for home is "Earth", but like before, if you don't provide a default then you need to change String home to String? home.

Private fields

If you need private fields then you can use [] square brackets:

class User {
  int? _id;
  User([this._id]);
}

User user = User(3);

or do as the accepted answer says and use an initializer list:

class User {
  int? _id;
  User({int? id}) 
    : _id = id;
}

User user = User(id: 3);

Named required parameters

Named parameters are optional by default, but if you want to make them required, then you can use the required keyword:

class User {
  final String name;
  final int age;
  final String home;

  User({
    required this.name,
    required this.age,
    this.home = 'Earth',
  });
}

User user1 = User(name: 'Bob', age: 34);
User user2 = User(name: 'Bob', age: 34, home: 'Mars');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...