一尘不染

初始化形式参数不能在工厂构造函数中使用

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

如何解决?


阅读 258

收藏
2020-08-13

共1个答案

一尘不染

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,
    );
  }
}
2020-08-13