what does <RandomWords> mean? what is this grammar of Dart language?

class RandomWords extends StatefulWidget {
  @override
  State createState() {
  return new RandomWordsState();
 }
}

class RandomWordsState extends State<RandomWords>{
  @override
  Widget build(BuildContext context) {

    return new Scaffold(

    );
 }
}

what does <RandomWords> mean? what is this grammar of Dart language?


Solution 1: Naslausky

You are specifying what State this state is about, in the same way that when you say something like:

List<String> a;

You are saying what this List is made of.

In another words, it means the State class is a Generic class.

In the documentation of List class you will see they actually refer to it as: List<E> class. So, whatever type you put in the List, all of the methods related that contains E (as a argument or as a return) will have the signature adjusted accordingly, i.e.:

last ↔ E
Returns the last element.

As you can see, the last method returns the same type that the List contains, which is the expected.

The use of this is mostly for type safety, so if you try to insert a number into a List< String>, the compiler will know and will detect the mistake.

Also, if you're the one developing a Generic class, it will help avoid code duplication, because you won't have to write a implementation for each possible List type in the world.

When defining your class, you can do something as follows (Example from dart Language Tour):

abstract class Cache<T> {
  T getByKey(String key);
  void setByKey(String key, T value);
}

And, in their words:

In this code, T is the stand-in type. It’s a placeholder that you can think of as a type that a developer will define later.

Also, as a last tip, we can see on the documentation of the State class linked above that the generic type needs to be something that inherits from Stateful Widget, so you don't try to create a State< Int>, for example.

State < T extends StatefulWidget > class