初始化形式参数不能在工厂构造函数中使用
问题内容:
我正在尝试在我的课程中添加单例模式,但收到Iniliziating formal parameters can't be used in factory constructors
错误。这是我尝试过的:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final String email;
final String token;
final bool wordtestCompleted;
User.forJson({this.email, this.token, this.wordtestCompleted})
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
static final User _singleton = User._internal();
factory User({this.email, this.token, this.wordtestCompleted}) {
return _singleton;
}
User._internal();
}
如何解决?
问题答案:
this.
在构造函数中使用参数初始化成员的语法方式仅在普通构造函数中有效,而在factory
构造函数中则无效。(factory
构造函数没有this
对象!)
相反,您将需要手动将factory
构造函数的参数转发给实际的构造函数。例如:
class User {
static User _singleton;
final String email;
final String token;
final bool wordtestCompleted;
User._internal({this.email, this.token, this.wordtestCompleted});
factory User({String email, String token, bool wordtestCompleted}) {
return _singleton ??= User._internal(
email: email,
token: token,
wordtestCompleted: wordtestCompleted,
);
}
}