dart - 构造函数可选参数

有没有办法设置构造函数可选参数? 我的意思是:

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

表示

Named option parameters can't start with an underscore.

但是我需要这个字段作为私有(private)字段,所以,我现在迷路了。

最佳答案

对于 future 的观众来说,这是一个更普遍的答案。

位置可选参数

[ ] 方括号将可选参数括起来。

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');

如果你不提供默认值,可选参数需要可以为空:

class User {

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

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

命名可选参数

{ } 花括号包裹可选参数。

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');

home 的默认值是“Earth”,但和以前一样,如果您不提供默认值,则需要将 String home 更改为 String ?主页.

私有(private)领域

如果您需要私有(private)字段,则可以使用 [] 方括号:

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

User user = User(3);

或者按照公认的答案执行并使用初始化列表:

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

User user = User(id: 3);

命名的必需参数

命名参数默认是可选的,但是如果你想让它们成为必需的,那么你可以使用 required 关键字:

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');

https://stackoverflow.com/questions/52449508/

相关文章:

flutter - Flutter 中 MaterialApp 类中的构建器属性的示例?

flutter - Flutter中的水平列表列表

flutter - Flutter中如何返回刷新上一页?

flutter - 如何防止 AlertDialog 不通过点击外部关闭?

flutter - 在 mac 和 windows 之间共享解决方案时对包的路径文件引用不正确

dart - 小部件内的 flutter 循环

dart - 我们如何在flutter中更改appbar背景颜色

dart - 如何调整 ShowDialog 子项的大小

image - 如何在 Flutter 中裁剪图像?

dart - 在 TextInputType 更改后 Controller 重置的 Flutter