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>();
}
其中一种方法正在以下工作
#1 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是唯一的选择。
总之,我不知道什么时候使用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;
},
)
推荐阅读
- raspberry-pi - 在 Raspberry Pi 网络附加存储 (NAS) 上安装 Anaconda3 时权限被拒绝
- sql-server - SQL Server 中的 bcp 命令未在 Excel 中生成完整数据
- oracle - 将 Oracle Reports 12c 保存为 PDF 文件
- java - 关于 Java 嵌套 Enum 类型
- android - 未解决的参考:android build failed with kotlin dsl(可在空项目中重现)
- dart - 为什么 Dart 中的类构造函数有一个冒号 (:)?
- php - php解析没有create_function和eval的函数
- matlab - 如何在图像中将人体与背景分开
- python - 如何将多个字典添加到主字典中的键?下面给出示例
- sql - ListAgg 和其他列选择