您可以Union type
使用freezed包使您的类 a 并使用如下所示的折叠方法来查看使用了什么构造函数:
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