简体   繁体   中英

How to Update a Factory constructor for Dart with Null Safety and Instantiate?

I have a problem that seems simple to me; yet, I cannot figure it out.

I have been studying Dart with a few out-of-date books. And understandably, I have encountered a problem that I can't solve. The book that I am following is 'Flutter for Beginners' by Alessandro Biessek (2019) under the Factory constructors Section. The following code comes from the book (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}

My Questions:

  1. How can this code be updated to become null safe?
  2. How to instantiate the code? How do I make a Student or Employee? I have a mind-blank here.
  3. How often are Factory constructors used?

What I have tried: 1a) I tried to set the parameters firstName and lastName = ''. 1b) I have also tried to remove the [] from the constructor and the factory constructor. 2) I don't understand how to instantiate a factory Person. However, I have tried the following to instantiate it:

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

It was not successful in DartPad.

Any help would be appreciated.

Since your class attributes can be null you need to add the ? . Another problem in your code is that Student and Employee have a constructor with two arguments but in your factory Person.fromType you call it without any arguments.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM