flutter - 初始化形式参数不能在工厂构造函数中使用
问题描述
我正在尝试在我的班级中添加单例模式,但我收到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,
);
}
}
推荐阅读
- python - 如何用正确的 unicode 字符替换转义的 unicode 字符?
- javascript - 如何将对象转换为对象数组?并按 obj.value 排序?
- php - PHP是否等待mysql查询结果?
- javascript - VBA 网络爬虫从 JavaScript 表单访问搜索结果
- java - 如何将 getChildFragmentManager 与扩展对话框片段的类一起使用
- c# - WPF不确定如何在动态创建的堆栈面板中更改文本框的背景
- java - Mybatis如何运行sql“desc表”
- r - 获取"c(\"a\", \"b\")"格式的数据
- charts - Xamarin.Forms 检测图表上的垂直/水平缩放
- xmonad - 如何在 XMonad 的 Stackset 中获取 Window 的索引?