首页 > 解决方案 > 通用 TypeDef 不适用于自定义类

问题描述

我想创建一个泛型但带有一些在类外部具有外部的class(Test< T, F>)变量( ) 。分配运行良好,但正如屏幕截图所示失败。_cellBuildertypedef type(CellBuilder)testAStringtestB

当我从中删除<Product>testB,我得到一个不同的错误。

type '(Product) => Widget is not a subtype of type (dynamic) => Widget

相当混乱。请问有什么帮助吗?

在此处输入图像描述

void main() {

  testA<String>(String content) {
    print(content);
  }

  Widget testB<Product>(Product item) {
    print(item.a);
  }

  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    Test<int, Product> c = Test(testA, testB);
    c.eval();
  });
}

class Product {
 final String a;
 Product(this.a);
}

typedef CellBuilder<F> = Widget Function(F item);
typedef testString<T>(T text);

class Test<T, F> {
  final testString _f;
  final CellBuilder _cellBuilder;
  Test(testString this._f, CellBuilder this._cellBuilder);
  eval() {
    _f("hello");
    _cellBuilder(Product("world"));
  }
}

标签: genericsdartflutter

解决方案


应该:

Widget testB(Product item)

不是通用函数:

Widget testB<Product>(Product item)

Product是一个通用标识符,而不是您期望的参数类型。

如果您以自定义方式编写:

Widget testB<T>(T item)

该错误现在应该是有意义的。


推荐阅读