A
A
ameame2019-11-08 21:34:05
Dart
ameame, 2019-11-08 21:34:05

How do Stateless and Stateful widgets and generics work in Dart?

How do Stateless and Stateful widgets and generics work in Dart?
I've read the documentation and it's still not entirely clear.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiT, 2020-01-12
@MiT_73

StatelessWidget - Recommended for immutable widgets. These are widgets that do not have an internal state, depend only on the configuration parameters and on the parent widgets.
Here are some widgets that inherit from StatelessWidget:
The simplest construct to create a widget from the superclass StatelessWidget is:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Text('my text');
  }
}

StatelessWidget - needed where the internal state is one and it is formed by parameters and data that we know in advance.
StatefulWidget - recommended for mutable widgets with mutable internal state (State). A mutable state is a change in the internal state of a class instance depending on some event (by pressing, time, etc.). To do this, you need to create a widget that inherits StatefulWidget.
Here are some widgets that inherit from StatefulWidget:
The simplest construct to create a widget from the StatefulWidget superclass is:
class MyWidget extends StatefulWidget {
  @override
  createState() => new MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {

  @override
  initState() {
    super.initState();
    // ...
  }

  @override
  Widget build(BuildContext context) {
    return new Text('my text');
  }
}

StatefulWidget - needed when there is more than one internal state and they can replace each other.
Generics or generics allow you to add flexibility to the program and get away from hard binding to certain types. Sometimes it is necessary to define a function in such a way that it can use data of any type. Here is a simple example to help you understand what Generics are:
void main (){
    Person bob = Person("324", "Bob");
    print(bob.id.runtimeType);  // String
    Person sam = Person(123, "Sam");
    print(sam.id.runtimeType);  // int
}
 
// T это Generic, если его не было, 
//нам пришлось-бы использовать несколько классов для определения идентификатора пользователя, 
//но в данном случае он Generic и мы можем передавать в него любой тип данных.
class Person<T>{
    T id;   // идентификатор пользователя
    String name; // имя пользователя
    Person(this.id, this.name);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question