[英]What is the difference between generics and dynamic in dart?
让我介绍一下为什么我遇到这个问题的错误。 (详情请看这里)
type '(String, String) => bool' is not a subtype of type '(dynamic, String) => bool'
这是material_search的错误, 解决方法是:
- _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 时似乎发生了该问题。
所以,我在这里得到了这些问题,
编辑:让我提供一个简单的例子来使问题更清楚:
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>();
}
Component<CoolType>( geneticFunc: (CoolType cool, String keyword){ return false; }, );
#2
Component<CoolType>( geneticFunc: (dynamic cool, String keyword){ return false; }, );
答案#2有效,这意味着我什至不需要 generic ,只需使用dynamic 。 如果您使用#1 ,有时在运行时甚至没有错误,您可能会在那里停留一整天。
有一个正式的讨论在这里说,T公司将始终在运行时动态的,所以#2是唯一choosen。
总之,我不知道什么时候使用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;
},
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.