Вы можете сделать свой класс 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