在 Dart 中,是否可以在单例中传递参数?

In Dart, is it possible to pass an argument in a singleton?

class Peoples {
  late int id;
  late String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples() {
    return _inst;
  }
}

我有这个单身人士class。这确保了只会创建 class 的一个实例。所以,即使有人试图实例化它,他们也会使用同一个实例。我可以创建和设置值,例如:

  Peoples ps1 = Peoples();
  Peoples ps2 = Peoples();

  ps1.id = 1;
  ps1.name = "First";

  ps2.id = 2;
  ps2.name = "Second";

是否可以像这样实例化和设置值:

  Peoples ps1 = Peoples(1, "First");
  Peoples ps2 = Peoples(2, "Second");

所以,现在“ps1”和“ps2”都会有 (2, "Second")。

好的! 您需要将参数传递给工厂方法,然后您需要使用引用的实例更新属性。

例如,您有

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples() {
    return _inst;
  }
}

如果你应用我的解决方案,那么你有

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples({int id, String name}) {
    _inst.id = id
    _inst.name = name
    return _inst;
  }
}

有了这个你的问题应该得到回答 有关工厂和参数的更多信息,请访问

https://dart.dev/guides/language/language-tour

工作示例

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();


  factory Peoples(int id, String name) {
    _inst.id = id;
    _inst.name = name;
    return _inst;
  }
}

void main() {
  print("Instance of = " + Peoples(0, "Dylan").name);
  print("Instance of = " + Peoples(1, "Joe").name);
  print("Instance of = " + Peoples(2, "Maria").name);
}

我想回答展示一种通过向它传递参数来创建单例的方法,以及如何在第一次创建它后“锁定”它的值。

class People {
  static final People _inst = People._internal();
  People._internal();

  factory People(int id, String name) {
    assert(!_inst._lock, "it's a singleton that can't re-defined");
    _inst.id = id;
    _inst.name = name;
    _inst._lock = true;
    return _inst;
  }
  
  int id;
  String name;
  bool _lock = false;
}

void main() {
  var people = People(0, 'Dylan');
  try{
    print('Instance of = ' + People(0, 'Joe').name);
    print('Instance of = ' + People(1, 'Maria').name);
    print('Instance of = ' + People(2, 'Ete sech').name);
  } finally {
    print('Instance of = ' + people.name);
  }
}

不能在我的机器上 运行,29/3/2022

计算机说:“Non-nullable 实例字段 'id' 必须初始化。”

我不能发表评论,所以写下这个答案:

在成员变量前添加关键字late会有帮助:

class Peoples {
  late int id;
  late String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();


  factory Peoples(int id, String name) {
    _inst.id = id;
    _inst.name = name;
    return _inst;
  }
}