我需要使用具有两个类的回调 - 一个基类和一个派生类。我需要将该参数类型作为回调的参数传递,我曾尝试使用基类作为 typedef 中的参数类型,但出现以下错误:
The argument type 'bool Function(EmployeeDetails)' can't be assigned to the parameter type 'bool Function(SalesDetails)?'.dart(argument_type_not_assignable).
但我需要一种方法来提供任何一个类作为参数而不是单个基类。
我也尝试在 typedef 中使用 dynamic 作为参数类型,但仍然无法解析并显示以下错误:
The argument type 'bool Function(SalesDetails)' can't be assigned to the parameter type 'bool Function(dynamic)?'.dart(argument_type_not_assignable)
这是我完成的代码:
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Employee emp = Employee((SalesDetails sales) {
EmployeeDetails emp = sales as EmployeeDetails;
return true;
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: Text(
func(emp),
)),
);
}
}
String func(Employee sales) {
String str = 'value';
return str;
}
typedef EmployeeCallback = bool Function(dynamic details);
class Employee {
Employee(this.onValue);
EmployeeCallback? onValue;
}
class SalesDetails {
SalesDetails(this.name, this.id);
final String name;
final num id;
}
class EmployeeDetails extends SalesDetails {
EmployeeDetails(this.empid, String name, num id) : super(name, id);
final num empid;
}
我需要传递任何类作为参数类型,如下所述:
答案 0 :(得分:0)
您的错误基本上是说:“您提供了一个 bool Function(EmployeeDetails)
,但您需要提供一个 bool Function(SalesDetails)?
”
因为这是一个面向对象的问题,所以让我们使用动物:
class Animal {
void eat() => print('eating');
}
class Dog extends Animal {
void bark() => print('barking');
}
使用这些类,您的错误看起来像:“您提供了 bool Function(Dog)
但您需要提供 bool Function(Animal)?
”
这是有道理的:参数需要一个可以处理任何 Animal
的函数,但是你给了它一个只知道如何处理 Dog
的函数,例如:
void feedAnimals(bool Function(Animal) shouldFeed) {
allAnimals // a List<Animal> from somewhere else in our code
.where(shouldFeed)
.forEach((animal) => animal.feed());
}
想象一下,您试图将 bool Function(Dog)
传递给这个:
final void Function(Dog) shouldFeedDog = (dog) => dog.tailLength > 10;
feedAnimals(shouldFeedDog); // compile error
如果这段代码没有给出编译时错误,您将尝试对 .tailLength
中的所有项目调用 allAnimals
,但并非所有 Animal
都有尾部,所以这代码不安全。
要修复您的错误,您可以定义一个符合您期望的 bool Function(SalesDetails)
:
final bool Function(SalesDetails) checkSalesDetails = (details) {
// perform checking logic
};
// or
bool checkSalesDetails(SalesDetails details) {
// perform checking logic
}
Or, you can change the place you provide the function to be happy with a `bool Function(EmployeeDetails)`. In the animal analogy, this might look like:
```dart
void feedDogs(bool Function(Dog) shouldFeedDog) {
allAnimals
.whereType<Dog>() // filter out non-Dogs, return an Iterable<Dog>
.where(shouldFeedDog)
.forEach((dog) => dog.feed());
}