【问题标题】:How to Update a Factory constructor for Dart with Null Safety and Instantiate?如何使用 Null 安全和实例化更新 Dart 的工厂构造函数?
【发布时间】:2026-01-23 03:55:02
【问题描述】:

我有一个对我来说似乎很简单的问题;但是,我想不通。

我一直在用一些过时的书来学习 Dart。可以理解的是,我遇到了一个我无法解决的问题。我正在关注的书是 Alessandro Biessek(2019 年)在 Factory constructors Section 下的“Flutter for Beginners”。以下代码来自本书(pg 48-49):

class Student extends Person {
Student(firstName, lastName) : super (firstName, lastName);
}

class Employee extends Person {
Employee(firstName, lastName) : super (firstName, lastName);
}

class Person {
  String firstName;
  String lastName;
  
  Person([this.firstName, this.lastName]);
  
  factory Person.fromType([PersonType type]){
    switch(type){
      case PersonType.employee:
        return Employee();
      case PersonType.student:
        return Student();
    }
    return Person();
  }
  
  String getfullName() => '$firstName $lastName';
}

enum PersonType { student, employee}

我的问题:

  1. 如何更新此代码以确保为 null 安全?
  2. 如何实例化代码?我如何制作学生或员工?我对此一头雾水。
  3. Factory 构造函数的使用频率如何?

我尝试过的: 1a) 我尝试设置参数 firstName 和 lastName = ''。 1b)我还尝试从构造函数和工厂构造函数中删除 [] 。 2)我不明白如何实例化工厂人员。但是,我尝试了以下方法来实例化它:

void main() {
Person.fromType(PersonType.employee)
  ..firstName = 'Clark'
  ..lastName = 'Kent';
}

在 DartPad 中没有成功。

任何帮助将不胜感激。

【问题讨论】:

  • 你能告诉我应该如何使用这个Person 类吗?创建后是否可以更改名字/姓氏。我们应该能够创建没有名字和/或姓氏的人吗?
  • 这本书没有具体说明,julemand101。但是,我认为在创建时应该有不能改变的名字和姓氏。
  • 好的,但这也意味着您的 Person.fromType 工厂构造函数应该将名字/姓氏作为参数的一部分,因为我们在创建对象时需要知道这些信息。
  • 另外,当你用 [] 指定可选的位置参数时,你应该给它一个默认值或者让它可以为空,因为如果没有提供参数,我们需要处理这种情况。

标签: flutter dart factory


【解决方案1】:

由于您的 类属性 可以为 null,您需要添加 ?。 您的代码中的另一个问题是 StudentEmployee 有一个带有两个参数的构造函数,但在您的 factory Person.fromType 中您调用它时没有任何参数。

class Person {
  String? firstName;
  String? lastName;
  
  Person([this.firstName, this.lastName]);
  
  factory Person.fromType(Person person, [PersonType? type]){
    switch(type){
      case PersonType.employee:
        return Employee(person.firstName, person.lastName);
      case PersonType.student:
        return Student(person.firstName, person.lastName);
      default:
        return person;
    }
 
  }
  
  String getfullName() => '$firstName $lastName';
}
final Person person = Person('FirstName', 'LastName');
  
final Student student = Person.fromType(Person('WithoutLastName'), PersonType.student) as Student;
  
final Employee employee = Person.fromType(person, PersonType.employee) as Employee;

【讨论】:

    最近更新 更多