目标:每当用户按下该按钮时,在FlatButton
周围绘制边框。
换句话说:onPressed()
被调用? -> DrawBorder()
用例:最终的UI应允许用户选择多个按钮,这些选择的按钮应带有边框,以使用户知道已选择它们。
问题:无法以编程方式绘制边框,更不用说在同一UI中具有多个按钮(大约9个按钮左右)。
按钮代码:
FlatButton(
color: kWhite,
onPressed: () {},
child: Image.asset('assets/images/gucci.jpg'),
shape: RoundedRectangleBorder( //Draw when user clicks on the button
side: BorderSide(
color: kDarkTitleColor, width: 1),
),
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
),
您可以像这样将按钮包装在StatefulWidget
中:
class BorderedFlatButton extends StatefulWidget {
@override
_BorderedFlatButtonState createState() => _BorderedFlatButtonState();
}
class _BorderedFlatButtonState extends State<BorderedFlatButton> {
bool isSelected = false;
@override
Widget build(BuildContext context) {
return FlatButton(
color: kWhite,
onPressed: () {
print(isSelected);
setState(() {
isSelected = !isSelected;
});
},
child: Image.asset('assets/images/gucci.jpg'),
shape: RoundedRectangleBorder(
side: BorderSide(
color: isSelected ? kDarkTitleColor : Colors.transparent, width: 1),
),
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
);
}
}
PS:在这里我添加了一个状态变量isSelected
,该状态变量指示是否选择了按钮。