让我介绍一下我遇到这个问题的错误。 ( Detail here )
type '(String, String) => bool' is not a subtype of type '(dynamic, String) => bool'
这是来自 material_search 的错误, 和 solution是:
- _filter(T v, String c) {
+ _filter(dynamic v, String c) {
- onSelect: (T value) => Navigator.of(context).pop(value),
+ OnSelect: (dynamic value) => Navigator.of(context).pop(value),
将所有泛型类型 T
更改为动态类型,并且问题似乎是在 dart 2 出现时发生的。
所以,我在这里遇到了这些问题,
- dart 中的generics 和dynamic 有什么区别?
- 仅适用于泛型或另一方面的限制是什么?在上述问题中,这仅适用于动态。
编辑: 让我提供一个简单的例子来使问题更清楚:
用遗传定义一个类
typedef bool GeneticFunction<T>(T geneticData, String key);
class Component<T> extends StatefulWidget {
Component({this.geneticFunc});
final GeneticFunction<T> geneticFunc;
@override
_componentState<T> createState() => _componentState<T>();
}
其中一种方法在下面工作
#1 Component<CoolType>(
geneticFunc: (CoolType cool, String keyword){
return false;
},
);
#2
Component<CoolType>(
geneticFunc: (dynamic cool, String keyword){
return false;
},
);
答案 #2 有效,这意味着我甚至不需要通用,只需动态。如果你使用#1,有时甚至运行时没有错误,你可能会卡在那里一整天。
有官方讨论here ,表示 T 在运行时总是动态,所以 #2 是唯一的选择。
总而言之,我不知道什么时候使用generic,而且由于上面的结果,现在似乎总是使用dynamic。
最佳答案
抱歉,我的问题拖延了很长时间,这个问题的真正问题是在 StatefulWidget 中使用泛型的正确方法是什么?
让我们看一下原始代码:
class Component<T> extends StatefulWidget {
Component({this.data, this.geneticFunc});
final T data;
final GeneticFunction<T> geneticFunc;
void test()
{
var testFunc = geneticFunc;
testFunc(data, "123");
}
@override
_ComponentState<T> createState() {
return _ComponentState<T>();
}
}
class _ComponentState<T> extends State<Component>
{
@override
void initState() {
print("test one");
var a = widget.geneticFunc;
print("test two");
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(width: 20, height: 20,);
}
}
你猜怎么着?只记得添加 <T>
当扩展一个泛型类时,问题就解决了。
class _ComponentState<T> extends State<Component<T>>
所以问题type '(String, String) => bool' is not a subtype of type '(dynamic, String) => bool'
再也不会打扰我了。
下面的代码现在应该可以工作了。
Component<CoolType>(
geneticFunc: (CoolType a, String key){
return false;
},
)
关于dart - Dart 中的泛型和动态有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106082/