list - 如何在列表中选定的单个按钮上加边框
问题描述
我有一个按钮列表,我想选择其中一个,红色边框出现 onClick。再次点击,边框消失。我怎样才能做到这一点?就我而言,当我单击它时,一次圈出列表中的所有按钮。请教我。
解决方案
首先,您必须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: () {},
),
键应该是唯一的字符串。
推荐阅读
- php - SQL 排序规则未正确显示
- node.js - Node js Serial port stops receiving data after a while
- git - Remove GIT from OSX Catalina
- android - AdMob Adaptive/Smart Banner Background Color Android
- android - How can you lock the volume control programmatically
- material-table - How to reload data in material table when state changes?
- amazon-web-services - 无法识别的令牌“$context”:期待(“true”、“false”或“null”)AWS VTL
- python - 为什么在 Django 的登录表单中显示错误?
- javascript - Django 项目中的 Jquery 脚本未检测到表单提交
- ag-grid - Angular 10 ag-grid 无法设置属性“setRowData”,因为 gridOptions.api 未定义