10

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

18

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.