Object< type>是什么? Dart中的语法含义? [英] What does the Object<type> syntax mean in Dart?
问题描述
在以下代码示例中,来自 flutter docs :
In the following code example, from the flutter docs:
class RandomWords extends StatefulWidget {
@override
createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
@override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
return Text(wordPair.asPascalCase);
}
}
State< ; RandomWords>
语法意味着什么?
我知道您可以使用此语法为集合中包含的对象(例如列表)指定类型-列表< String>
I understand that you can specify the type for the objects contained in a collection, like lists, using this syntax - List <String>
但是我不明白 State< RandomWords>背后的动机;
。
此外,如何在 RandomWords
中引用 RandomWordsState
声明,并在 RandomWordsState
声明中引用 RandomWords
吗?
Moreover, how can you reference RandomWordsState
in RandomWords
declaration and also reference RandomWords
in RandomWordsState
declaration? Shouldn't that cause a circular reference error or something?
我来自动态类型的语言,例如python,这对我来说有点奇怪,有人可以指点我吗?
I come from dynamically typed languages like python, and this looks a little odd to me, can someone please point me to the right place?
推荐答案
< RandomWords>
是通用的类型参数传递给 State
类。
<RandomWords>
is a generic type parameter passed to the State
class.
State
类看起来像
abstract class State<T extends StatefulWidget> extends Diagnosticable {
和 RandomWords
将被传递到 T
类型参数,该参数具有一个约束, T
必须是 StatefulWidget的子类
。
and RandomWords
will be passed to the T
type parameter which has a constraint that T
needs to be a subclass of StatefulWidget
.
State
还有一个使用类型参数的字段和获取器
State
also has a field and getter where the type parameter is used
T get widget => _widget;
T _widget;
这会导致小部件
类型的属性,该属性提供正确的自动补全和类型检查其子类 RandomWordsState
假设您有
class RandomWords extends StatefulWidget {
RandomWords({this.fixed});
final WordPair fixed;
@override
createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
@override
Widget build(BuildContext context) {
// vvvv here we can access `fixed` in a strongly typed manner
final wordPair = widget.fixed ?? WordPair.random();
return Text(wordPair.asPascalCase);
}
}
另请参见 https://www.dartlang.org/guides/language/language-tour#generics
这篇关于Object< type>是什么? Dart中的语法含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!