首页 > 解决方案 > 飞镖中的泛型和动态有什么区别?

问题描述

让我介绍一下为什么我遇到这个问题的错误。(这里详细

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 出现时。

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

  1. 飞镖中的泛型动态有什么区别?
  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,因为上面的结果。

标签: dartflutter

解决方案


很抱歉我的问题耽搁了很长时间,这个问题的真正问题是什么是使用 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;
  },
)

推荐阅读