dart - Dart 中的泛型和动态有什么区别?

标签 dart flutter

让我介绍一下我遇到这个问题的错误。 ( 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 出现时发生的。

所以,我在这里遇到了这些问题,

  1. dart 中的genericsdynamic 有什么区别?
  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 有效,这意味着我甚至不需要通用,只需动态。如果你使用#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/

相关文章:

dart - 参数长度未知的自定义元数据?

dart - Streambuilder 没有收到一些快照数据

android - 如何在一定时间后在 Flutter 中切换 Widgets?

dart - 带有 const 关键字的 flutter 变量

DART:如何编写返回 Future 的耗时函数

dart - 通过 SignalR 加载数据时在 AngularDart 中重新绑定(bind)页面

flutter - 重用输入验证器

flutter - 错误 :flutter/lib/ui/ui_dart_state. cc(199) 未处理的异常:对空值使用空检查运算符

dart - Flutter:_InternalLinkedHashMap 没有实例 > 方法 'cast'

linux - 从 flutter 应用程序关闭/重新启动 Linux 机器