gpt4 book ai didi

flutter - 如何检查是否使用 dart 中的命名构造函数创建了元素?

转载 作者:行者123 更新时间:2023-12-03 03:22:37 25 4
gpt4 key购买 nike

我想知道是否可以检查我使用哪个构造函数在 dart 的 if 语句中创建创建的元素。

我想做的一个简单的例子:

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")
}

有没有办法做到这一点?谢谢您的回答。

最佳答案

您可以将您的类(class)设为 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

关于flutter - 如何检查是否使用 dart 中的命名构造函数创建了元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61560487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com