I have defined a custom widget for ElevatedButton, and I want to make the shape field optional as shown below and use the initial value when no value is passed, but when I write it as above, the following error occurs. ..
class GradientElevatedButton extends StatelessWidget {
GradientElevatedButton({
Key? key,
required this.onPressed,
required this.child,
required this.colors,
this.shape = RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),//←here
),
}) : super(key: key);
final Widget child;
final void Function() onPressed;
final List<Color> colors;
final OutlinedBorder shape;
//error
The default value of an optional parameter must be constant.
Maybe it means that the BorderRadius.circular constructor is not const,
How should I write if I want to use the following OutlinedBorder as the default value? RoundedRectangleBorder ( borderRadius: BorderRadius.circular (30), )
BorderRadius.circular is not a const constructor, so you cannot use it as a default value of a const constructor.
However, if you look at the implementation:
/// Creates a border radius where all radii are [Radius.circular(radius)].
BorderRadius.circular(double radius) : this.all(
Radius.circular(radius),
);
It uses BorderRadius.all and Radius.circular and both of them are const constructor.
So you can replace
BorderRadius.circular(shape)
with
BorderRadius.all(Radius.circular(30))
Here is your updated code sample:
class GradientElevatedButton extends StatelessWidget {
GradientElevatedButton({
Key? key,
required this.onPressed,
required this.child,
required this.colors,
this.shape = const RoundedRectangleBorder( // <- Don't forget the const keyword
borderRadius: BorderRadius.all(Radius.circular(30)),//←here
),
}) : super(key: key);
final Widget child;
final void Function() onPressed;
final List<Color> colors;
final OutlinedBorder shape;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With