Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to set a value including BorderRadius.circular as the default value of the argument of the constructor

Tags:

flutter

dart

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), )

like image 677
森口万太郎 Avatar asked Nov 19 '25 12:11

森口万太郎


1 Answers

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;
like image 185
Valentin Vignal Avatar answered Nov 21 '25 03:11

Valentin Vignal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!