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), )
CodePudding user response:
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;
CodePudding user response:
I think this is not what you want, but sometime it helps others.
import 'package:flutter/material.dart';
class GradientElevatedbutton extends StatelessWidget {
const GradientElevatedbutton({
Key? key,
required this.onPressed,
required this.child,
required this.colors,
this.shape = 30,
}) : super(key: key);
final Widget child;
final void Function() onPressed;
final List<Color> colors;
final double shape;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(shape),
),
),
child: Text('click'),
);
}
}
CodePudding user response:
This part of your code:
this.shape = RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
must be change to:
this.shape = const RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),