Flutter Stateful Widget set constructor default values

3,617

Your constructor name should be the class name. And to provide default values you just add an =defaultValue next to the variable in the constructor.

class CustomWidget extends StatefulWidget {
   final String buttonText;
   final Function onPressed;

   CustomWidget ({Key key, @required this.onPressed, this.buttonText = 'defaultString'}) :super(key: key);//this.buttonText='defaultString'

   @override
   _CustomWidgetState createState() => _CustomWidgetState();
}
Share:
3,617
Admin
Author by

Admin

Updated on December 23, 2022

Comments

  • Admin
    Admin over 1 year

    I have tried to create a custom stateful widget. But I can't find any reference on how to set default values on a constructor.

    As an example:

    class CustomWidget extends StatefulWidget {
       final String buttonText;
       final Function onPressed;
    
       CustomWidget({Key key, @required this.onPressed, this.buttonText}) : super(key: key);
    
       @override
       _CustomWidgetState createState() => _CustomWidgetState();
    }
    
    class _CustomWidgetState extends State<CustomWidget> {
       @override
       Widget build(BuildContext context) {
          return FlatButton(
             onPressed: widget.onPressed,
             child: Text(widget.buttonText),
          );
       }
    }
    

    When I create the widget as a child of another widget and include all of the properties it works perfectly

    child: CustomWidget(
       buttonText: 'Text of the button',
       onPressed: () {},
    )
    

    However when I leave the buttonText out the app crashes.

    child: CustomWidget(
       onPressed: () {},
    )
    

    A basic workaround is to simply add the line buttonText: ''. I don't always want to specifically address each of the custom widgets' properties when I create it.

    So my question is, how do I set default properties on the constructor? So when I do omit a property the app doesn't crash?