初始化形式参数不能在工厂构造函数中使用 [英] Iniliziating formal parameters can't be used in factory constructors

查看:111
本文介绍了初始化形式参数不能在工厂构造函数中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在类中添加单例模式,但是我收到初始化形式参数无法在工厂构造函数中使用错误。这是我尝试的方法:

i am trying add singleton pattern in my class but i receive Iniliziating formal parameters can't be used in factory constructors error. Here is what i tried:

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 构造函数。 (一个工厂构造函数没有这个对象!)

The syntactic sugar of using this. in constructor parameters to initialize members works only in normal constructors, not in factory constructors. (A factory constructor has no this object!)

您将改为需要将工厂构造函数的参数手动转发到实际的构造函数。例如:

You instead will need to manually forward your factory constructor's arguments to an actual constructor. For example:

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

这篇关于初始化形式参数不能在工厂构造函数中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆