如何在列表中选定的按钮上添加边框



我有一个按钮列表,我想选择其中一个,红色边框显示在Click上。再次点击,边框消失。我怎样才能做到这一点?就我所做的而言,当我点击它时,一次将列表中的所有按钮都圈起来。请教我。

首先,您必须为按钮创建一个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: () {},
),

密钥应该是唯一的字符串。

最新更新