Widget is a class? But why not call it just class and not widget. I know that every thing in the flutter is a widget and every class is a widget? Why though? Maybe call every class gadget or anything else I was wondering if my interviewer might ask me this question
A widget is a class that has the build method:
@override
Widget build(BuildContext context) {
return Container(...);
}
A normal class doesn't have a build method.
You also can make a widget:
@override
Widget build(BuildContext context) {
return Container(...); //Widget tree
}
var name;
var age;
var location;
//constructor
ClassName({this.name, this.age, this.location});
in the constructor you also can make things required:
var name;
var age;
var location;
//constructor
ClassName({@required this.name, this.age, this.location});
you put the constructor at the beginning of your class:
class WidgetName extends StatelessWidget {
//constructor
WidgetName({
@required this.name,
this.age,
this.location,
});
var name;
var age;
var location;
@override
Widget build(BuildContext context) {
return Container(...); //Widget tree
}
}
or extending StatefulWidget:
class WidgetName extends StatefulWidget {
var name;
var age;
var location;
//constructor
WidgetName({this.name, this.age, this.location});
@override
_WidgetNameState createState() => _WidgetNameState();
}
class _WidgetNameState extends State<WidgetName> {
//inside of this class you can get the data from the constructor like this: widget.name
@override
Widget build(BuildContext context) {
return Container(...);
}
}
and you can use the widget like a normal widget:
WidgetName(
name: "David",
age: 28,
location: "Sofia, Bulgaria",
),
I hope this answer helps you to understand the difference between a normal class and a widget
Simply, a widget is any class that inherits from the Widget
class, typically starting from StatefulWidget
or StatelessWidget
. A widget is expected to have a certain protocol... in particular, be part of the context tree and also be able to be moved in that tree. Most widgets contribute some view on the UI, but some don't, and are merely for settings like TextTheme
.
every flutter class is a Widgdet
not right
every flutter class (Widget build) is a Widgdet is right.
class will never be a widget
Widget it's more high level construction than class. Class it's foundation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.