user13848261
user13848261

Reputation:

How do I use non-constant values for optional parameters

I am trying to create a custom class for my FlutButton widget and when I try to specify the color property with square brackets I get this error:

The default value of an optional parameter must be constant.
class CustomFlatButton extends StatelessWidget {
  final String text;
  final Color color;
  final Color textColor;
  CustomFlatButton({
    this.text='Default sign in text', 
    this.color = Colors.white70, 
    this.textColor = Colors.grey[900] // this is what is causing the error [900]
  });

Is there a way to fix this without converting my widget into a stateful one?

In advance, thank you.

Upvotes: 2

Views: 835

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126704

You can use the initializer list to initialize your final instance fields with non-constant values:

class CustomFlatButton extends StatelessWidget {
  CustomFlatButton({
    this.text='Default sign in text', 
    this.color = Colors.white70, 
    Color textColor,
  }) : textColor = textColor ?? Colors.grey[900];
  
  final String text;
  final Color color;
  final Color textColor;
}

In this case, the left-hand of the textColor = textColor ?? Colors.grey[900] assignment corresponds to this.textColor and the right-hand textColor is referring to the constructor parameter. If no value is passed to the constructor, a default value is used using the ?? operator.


You can learn more about the initializer list here.
And you can learn more about the ?? operator here.

Upvotes: 1

Related Questions