首页 > 解决方案 > 如何在列表中选定的单个按钮上加边框

问题描述

我有一个按钮列表,我想选择其中一个,红色边框出现 onClick。再次点击,边框消失。我怎样才能做到这一点?就我而言,当我单击它时,一次圈出列表中的所有按钮。请教我。

标签: listflutterselectborder

解决方案


首先,您必须stateful widget为您的按钮创建一个,以跟踪它是否应该显示边框。这应该是这样的:

class MyButton extends StatefulWidget {
  @override
  _MyButtonState createState() => _MyButtonState();

  final Widget child;
  final void Function() onPressed;
  final Key key;
  final Color buttonPrimaryColor, buttonOnPrimaryColor, borderColor;
  final double borderWidth;
  MyButton({
    @required this.child,
    this.onPressed,
    this.key,
    this.borderColor = Colors.red,
    this.buttonPrimaryColor,
    this.buttonOnPrimaryColor,
    this.borderWidth = 1.0,
  });
}

class _MyButtonState extends State<MyButton> {
  bool showBorder = false;
  void toggleShowBorder() => setState(() => showBorder = !showBorder);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      key: widget.key,
      onPressed: widget.onPressed == null
          ? null
          : () {
              toggleShowBorder();
              widget.onPressed();
            },
      child: widget.child,
      style: ButtonStyle(
        // If showBorder == true, we show a red border
        shape: MaterialStateProperty.resolveWith(
          (_) => showBorder
              ? RoundedRectangleBorder(
                  borderRadius: BorderRadius.zero,
                  side: BorderSide(
                    color: widget.borderColor,
                    width: widget.borderWidth,
                  ),
                )
              : RoundedRectangleBorder(),
        ),
      ).merge(
        ElevatedButton.styleFrom(
          primary: widget.buttonPrimaryColor ??
              Theme.of(context).buttonTheme.colorScheme.primary,
          onPrimary: widget.buttonOnPrimaryColor ??
              Theme.of(context).buttonTheme.colorScheme.onPrimary,
        ),
      ),
    );
  }
}

用法很简单:

MyButton(
  child: Text('Press me'),
  onPressed: () {},
),

如果要更改按钮的颜色,可以通过传入参数来实现:

MyButton(
  borderColor: Colors.amber,
  buttonPrimaryColor: Colors.white,
  buttonOnPrimaryColor: Colors.black,
  child: Text('Press me'),
  onPressed: () {},
),

用于buttonPrimaryColor按钮的背景色buttonOnPrimaryColor用于按钮的前景色borderColor用于按钮的边框颜色(默认为红色)

您还可以使用borderWidth参数更改边框宽度,如下所示:(1.0默认情况下)

MyButton(
  borderWidth: 4.0,
  child: Text('Press me'),
  onPressed: () {},
),

传入参数也是一个好主意,key因为您正在使用按钮列表,如下所示:

MyButton(
  key: Key('some unique key'),
  child: Text('Press me'),
  onPressed: () {},
),

键应该是唯一的字符串。


推荐阅读