skip to Main Content

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


  1. You have it wrong: you need to use the this keyword instead of widget since your in the class instance.

    Instead of

    return Text(widget.text);
    

    Use:

    return Text(this.text);
    

    You would use widget. when you are working within the State class of a StatefulWidget and you need to access the properties of the widget in the corresponding StatefulWidget class.

    This is an example of when you would use widget.:

    class MyWidget extends StatefulWidget {
      final String text;
      
      const MyWidget({required this.text});
      
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      @override
      Widget build(BuildContext context) {
        return Text(widget.text);
      }
    }
    
    
    Login or Signup to reply.
  2. There is no need to utilize widget.text or this.text since this is a stateless widget.

    class MyWidget extends StatelessWidget {
    final String text;
    
    const MyWidget({required this.text});
    
    @override
    Widget build(BuildContext context) {
    return Text(text);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search