What does the Object syntax mean in Dart?

2019-02-27 20:39发布

问题:

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);
  }
}

What exactly does the State<RandomWords> syntax mean?

I understand that you can specify the type for the objects contained in a collection, like lists, using this syntax - List <String>

But I cannot understand the motive behind State<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?

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?

回答1:

<RandomWords> is a generic type parameter passed to the State class.

The State class looks like

abstract class State<T extends StatefulWidget> extends Diagnosticable {

and RandomWords will be passed to the T type parameter which has a constraint that T needs to be a subclass of StatefulWidget.

State also has a field and getter where the type parameter is used

  T get widget => _widget;
  T _widget;

This results in a property of the type of the widget which provides proper autocompletion and type checks in its subclass RandomWordsState

Assume you have

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);
  }
}

See also https://www.dartlang.org/guides/language/language-tour#generics



标签: dart flutter