我想设置一个包含BorderRadius的值.循环作为构造函数实参的默认值



我已经为ElevatedButton定义了一个自定义小部件,并且我想使形状字段可选,如下所示,并在没有传递值时使用初始值,但是当我像上面那样写时,发生以下错误:

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.

也许它意味着BorderRadius。循环构造函数不是const,

如果我想使用下面的OutlinedBorder作为默认值,我应该怎么写?RoundedRectangleBorder (borderRadius: borderRadius。圆形(30),)

BorderRadius.circular不是const构造函数,所以不能将其作为const构造函数的默认值。

但是,如果你看一下实现:

/// Creates a border radius where all radii are [Radius.circular(radius)].
BorderRadius.circular(double radius) : this.all(
Radius.circular(radius),
);

使用BorderRadius.allRadius.circular,它们都是const构造函数。

所以你可以替换

BorderRadius.circular(shape)

BorderRadius.all(Radius.circular(30))

下面是更新后的代码示例:

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;

我认为这不是你想要的,但有时它可以帮助别人。

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'),
);
}
}

这部分代码:

this.shape = RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),

必须改为:

this.shape = const RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),

最新更新