I have this code:
class MyWidget extends StatelessWidget {
final String text;
const MyWidget({required this.text});
@override
Widget build(BuildContext context) {
return Text(widget.text); // Accessing `text` using the `widget` keyword
}
this is my simple my code, but widget.text
is causing an error:
Undefined name 'widget'. Try correcting the name to one that is defined, or defining the name. widget.
2
Answers
You have it wrong: you need to use the
this
keyword instead ofwidget
since your in the class instance.Instead of
Use:
You would use
widget.
when you are working within theState
class of aStatefulWidget
and you need to access the properties of the widget in the correspondingStatefulWidget
class.This is an example of when you would use
widget.
:There is no need to utilize widget.text or this.text since this is a stateless widget.