【问题标题】:What type to be declared声明什么类型
【发布时间】:2020-05-12 11:04:34
【问题描述】:

所以有这样一个类

class Base<T extends BaseClass> extends StatefulWidget

并且我想使用该类而不直接提供扩展 BaseClass 的对象,而是通过构造函数传递一些东西。

class Something extends StatelessWidget {
  final /*what type I am supposed to give here*/ test;

  const Something({Key key, this.test}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Base<test>();
  }
}

我得到的错误警告是

'dynamic' doesn't extend 'BaseClass'.
Try using a type that is or is a subclass of 'BaseClass'.dart(type_argument_not_matching_bounds)

The name 'test' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'test'.dart(non_type_as_type_argument)

【问题讨论】:

标签: flutter dart types


【解决方案1】:

您可以通过“类型”声明,但不能从表示类的 Type 对象创建类的实例。

class Something<T extends BaseClass> extends StatelessWidget {
  // final Type test;

  // const Something({Key key, this.test}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Base<T>();
  }
}

创建一些小部件:

class NewClass extends BaseClass {}

Widget x = Something<NewClass>();

【讨论】:

  • 如果我不能从构造函数传递实例,我应该如何在 Base 中为 T 赋值?
  • 我添加了一个 create Something 小部件示例。
  • 太糟糕了,它不能完全工作,因为所有应该在 T 类中的字段都无法访问,只能访问 BaseClass
  • 当然,那只是访问已知接口。 dart.dev/guides/language/language-tour#generics
猜你喜欢
  • 2012-11-17
  • 2014-05-07
  • 2017-11-02
  • 1970-01-01
  • 2011-04-16
  • 2014-08-26
  • 2012-08-17
  • 2014-08-27
  • 1970-01-01
相关资源
最近更新 更多