Как проверить, был ли создан элемент с именованным конструктором в dart? - PullRequest
1 голос
/ 02 мая 2020

Мне было интересно, смогу ли я проверить, какой конструктор я использовал для создания созданного элемента в операторе if в dart.

Простой пример того, что я хочу сделать:

class Employee {
  int id;
  String name;
  String title;

  Employee.id(this.id);

  Employee.name(this.name);

  Employee.title(this.title);
}

Теперь у меня есть выражение if где-то в моем коде и я хочу проверить, использовал ли я конструктор Employee.id. В этом случае я бы сделал что-то вроде этого:

Employee e = new Employee.id(1)

//check if e was created with Employee.id constructur
if (e == Emploee.id) { 
   print(e.id)
} else {
   print("no id")
}

Есть ли способ сделать это? Спасибо за ваш ответ.

Ответы [ 2 ]

1 голос
/ 02 мая 2020

Вы можете сделать свой класс Union type с помощью пакета freezed и использовать методы свертывания, как показано ниже, чтобы увидеть, какой конструктор использовался:

 import 'package:freezed_annotation/freezed_annotation.dart';

part 'tst.freezed.dart';

@freezed
abstract class Employee with _$Employee {
  const factory Employee.id(int id) = IdEmployee;

  const factory Employee.name(String name) = NameEmployee;

  const factory Employee.title(String title) = TitleEmployee;
}

void main() {
  Employee employee1 = Employee.id(0);
  Employee employee2 = Employee.name('some name');
  Employee employee3 = Employee.title('some title');

  employee1.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the first statement

  employee2.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the second statement

  employee3.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the third statement


  print(employee1 is IdEmployee);
  print(employee1 is NameEmployee);
}

, и результат будет быть:

created using id contsrutor and id= 0
created using name const and name = some name
created using title const and title = some title
true
false
1 голос
/ 02 мая 2020

Вы можете определить частное свойство enum, чтобы установить личную информацию, подобную этой, и распечатать ее позже с помощью функции. Также не забудьте пометить ваши конструкторы factory.

enum _ConstructorType {
  Identifier,
  Name,
  Title,
}

class Employee {
  int id;
  String name;
  String title;
  _ConstructorType _constructorType;

  factory Employee.id(id) {
    return Employee._privateConstructor(_ConstructorType.Identifier, id: id);
  }

  factory Employee.name(name) {
    return Employee._privateConstructor(_ConstructorType.Name, name: name);
  }

  factory Employee.title(title) {
    return Employee._privateConstructor(_ConstructorType.Title, title: title);
  }

  Employee._privateConstructor(this._constructorType,
      {this.id, this.name, this.title});

  String constructorDescription() {
    return this._constructorType.toString();
  }
}

Если вам нужна эта информация не как строка, а как enum, вы всегда можете удалить подчеркивание и сделать эту информацию открытой. c для использования вне класса.

...