Object< type>是什么? Dart中的语法含义?

编程入门 行业动态 更新时间:2024-10-26 04:28:50
本文介绍了Object< type>是什么? 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); } }

另请参见 www.dartlang/guides/language/language-tour#generics

更多推荐

Object&lt; type&gt;是什么? Dart中的语法含义?

本文发布于:2023-11-09 06:12:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   含义   lt   amp   Object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!