9

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?

1 Answer 1

17

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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.