Flutter 如何为Button添加圆角

项目中有需要圆角按键的地方,百度之后发现都是在外部包裹一个widget的做法,用于OutlineButton会出现想象之外的异常现象,遂即寻求更靠谱的做法。

阅读MaterialButton的构造器,发现了ShapeBorder shape参数,我觉得它是一个突破点

final ShapeBorder shape;
const MaterialButton({
  Key key,
  @required this.onPressed,
  this.onHighlightChanged,
  this.textTheme,
  this.textColor,
  this.disabledTextColor,
  this.color,
  this.disabledColor,
  this.highlightColor,
  this.splashColor,
  this.colorBrightness,
  this.elevation,
  this.highlightElevation,
  this.disabledElevation,
  this.padding,
  this.shape,
  this.clipBehavior = Clip.none,
  this.materialTapTargetSize,
  this.animationDuration,
  this.minWidth,
  this.height,
  this.child,
}) : super(key: key);

ShapeBorder的说明: 

The shape of the button's [Material].
The button's highlight and splash are clipped to this shape. If the button has an elevation, then its drop shadow is defined by this shape as well

大意是这个参数决定按键的外观,好,就是它。

我找到了ShapeBorder,可惜的是它是abstract的,这表示它有一些方法没有实现,所以我转而寻找它的子类,我很快找到了一些类,经过挑选,我选择了RoundedRectangleBorder类,来让我们看看它可爱的构造方法

const RoundedRectangleBorder({
    this.side = BorderSide.none,
    this.borderRadius = BorderRadius.zero,
  }) : assert(side != null),
       assert(borderRadius != null);

简单明了堪称美妙的BorderRadius出现在我们眼前,其中all方法正是我们最需要的部分,通过对四个角设置radius参数决定圆角弧度

const BorderRadius.all(Radius radius) : this.only(
    topLeft: radius,
    topRight: radius,
    bottomLeft: radius,
    bottomRight: radius,
  );

在构造MaterialButton与它的子类按键时即可使用下面的shape,按键将会变成圆角。

ShapeBorder shape = const RoundedRectangleBorder(
          side: BorderSide.none,
          borderRadius: BorderRadius.all(Radius.circular(50)))

 

你可能感兴趣的:(Flutter 如何为Button添加圆角)