Danial Dezfouli
Danial Dezfouli

Reputation: 326

usage of generics in flutter dart

Can somebody explain the usage of <MyApp> ?

MyAppState is extended of State class , but what is MyApp?

I know OOP in php but can't understand this one.

class MyApp extends StatefulWidget{
  @override
  MyAppState createState() => new MyAppState();
}


class MyAppState extends State<MyApp>{
  @override
  Widget build(BuildContext context) {
    return new Scaffold(...);
  }
}

Upvotes: 9

Views: 7695

Answers (3)

Saed Nabil
Saed Nabil

Reputation: 6861

Always remember that State<T> class is implemented as a generic class

when you extend any generic class you have to specify the type for it which happen to be your statful widget concrete implementation and its name is MyApp

for every concrete implementation for the StatfulWidget class you need to define another concrete implementation of a class extending State<MyApp> and its name is MyAppState because State<T> is a generic class we code it as State<MyApp>

so as answer to your question

MyApp is the name of the concrete implementation of the class StatefulWidget

StatefulWidget -----> class not generic

MyApp -------------> concrete implementation for StatefulWidget class

State -----------> generic class of

MyAppState --> concrete implementation for State

Hope that help ..

Upvotes: 5

dragonfly02
dragonfly02

Reputation: 3669

<MyApp> is a type parameter of generic type State<T>. Not sure whether php has generics, but essentially generics allows you to reuse 'generic' code over a range of different types and in the meantime it provides more type safety e.g. generics prevents you accidentally adding a double to a list of int (List<int>) for example. A native example, again, would be generic list List<T> where the same operation like add item to a list can be applied to a list of int (List<int>) or a list of people or a list of anything.

Maybe check out this for generics in dart specifically.

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 89936

State<MyApp> is a State class that is specialized for the MyApp class. This allows it to have inheritable methods and properties that operate on or involve a MyApp widget.

For example, it allows MyAppState.widget to return the corresponding widget specifically as a MyApp widget instead of as a generic StatefulWidget. This is important if you then wanted to call MyApp-specific properties or methods on the returned widget.

Note that this is necessary because Flutter uses type-safe Dart and tries to do as much static type-checking as possible to minimize the cost of doing type-checking at runtime.

Upvotes: 1

Related Questions