首页 > 解决方案 > 初始化形式参数不能在工厂构造函数中使用

问题描述

我正在尝试在我的班级中添加单例模式,但我收到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();
}

如何解决?

标签: flutterdart

解决方案


使用构造函数参数初始化成员的语法糖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,
    );
  }
}

推荐阅读