简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM