【问题标题】:Iniliziating formal parameters can't be used in factory constructors初始化形式参数不能在工厂构造函数中使用
【发布时间】:2020-11-28 14:11:02
【问题描述】:

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

如何解决?

【问题讨论】:

  • 你打算如何创建这个单例?您为电子邮件、令牌等传递了什么值?如何?您是否正在尝试从一段 JSON 实例化单例,当然,您只会这样做一次?那么,这个单例的用例是什么?
  • @RichardHeap 这个类的主要目的是从 da api 接收数据并解析它。所以我想在解析完json字符串后将这个类用作Singleton

标签: flutter dart


【解决方案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,
    );
  }
}

【讨论】:

  • 您的回复。我应该如何从另一个类@jamesdlin 调用当前实例
  • 我不明白你的意思。在我提供的示例中,另一个类可以使用factory 构造函数,并且总是会返回相同的实例。
  • 例如,在 kotlin 中,我调用 User.getCurrentInstance 来获取相同的实例。但我不知道如何在这段代码中用 dart 调用它
  • 您可以简单地添加一个static getter 来访问_singleton(并要求调用者仅在构造一次User 后使用它)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多