Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Stateful Widget set constructor default values

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?

like image 834
RP Noeth Avatar asked Mar 02 '23 01:03

RP Noeth


1 Answers

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();
}
like image 145
ValdaXD Avatar answered Mar 06 '23 19:03

ValdaXD