Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass a class that extends StatelessWidget or StatefulWidget class

Tags:

flutter

Is it possible to create a class that extends a class extending StatelessWidget or StatefulWidget.

For example:

class MyButton extends StatelessWidget { final String label; Button({this.label}); @override Widget build(BuildContext context) {     return ButtonExample("label");} } 

then

class SubmitButton extends MyButton {    String label;    SubmitButton({Key key, this.label}) : super(label: label);  // then somehow extend the parent build and change only the color // or in case of StatefulWidget change a functionality } 

I tried to search for examples online but I had not success.

like image 696
M20 Avatar asked Jul 23 '18 10:07

M20


People also ask

What's the core difference between Statelesswidget and StatefulWidget?

A widget is either stateful or stateless. If a widget can change—when a user interacts with it, for example—it's stateful. A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets.

Should I use stateful or stateless?

Stateless widget is useful when the part of the user interface you are describing does not depend on anything other than the configuration information and the BuildContext whereas a Stateful widget is useful when the part of the user interface you are describing can change dynamically.

Why are StatefulWidget and state separate classes?

There are multiple reasons : Widgets are immutable. Since the Stateful widget extends Widget it, therefore, must be immutable too. Splitting the declaration into two classes allows both the Stateful widget API to be immutable and State to be mutable.


1 Answers

In Flutter composition is preferred over inheritance.
Widgets are not supposed to be extended, this is why there are no examples or tutorials how to do it.

Flutter has a strong focus on composition and the included widget library contains a lot of smaller widgets that do one thing well, that allow to compose them into custom widgets in many different ways.

like image 188
Günter Zöchbauer Avatar answered Sep 20 '22 10:09

Günter Zöchbauer