这是状态。例如,下面的小部件呈现一行按钮(它接受一个参数number,它是一个整数 - 要呈现的按钮的数量)。
当您单击一个按钮时,它会更新设置单击该按钮的索引的状态,将颜色从红色更改为蓝色。
注意:这可能不是您想要做的 - 您可能希望在单击时突出显示所有按钮。没关系,概念是您需要使用状态来跟踪点击次数。
class RowOfButtons extends StatefulWidget {
RowOfButtons({Key key, this.number}) : super(key: key);
final int number;
@override
RowOfButtonsState createState() => RowOfButtonsState();
}
class RowOfButtonsState extends State<RowOfButtons> {
int tapped;
@override
Widget build(BuildContext context) {
List<Widget> buttons = new List();
print(widget.number);
for(var i = 0;i < widget.number; i++) {
buttons.add(
SizedBox(
width: 40,
height:40,
child: Padding(
padding: EdgeInsets.all(5.0),
child: FlatButton(
color: tapped == i ? Colors.blue : Colors.red,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
splashColor: Colors.blueAccent,
child: Text("I am button '$i'"),
onPressed: () { setState(() { tapped = i; }); },
),
)
)
);
}
return Row(children: buttons);
}
}
编辑:通过创建自己的 Button 小部件,您可能会做得更好,如下所示:
class MyClickedButton extends StatefulWidget {
MyClickedButton({Key key, this.onPressed}) : super(key: key);
// allow the widget that renders this widget to pass
// in a callback for when the button is pressed
final Function() onPressed;
@override
MyClickedButtonState createState() => MyClickedButtonState();
}
class MyClickedButtonState extends State<MyClickedButton> {
bool pressed;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 40,
height:40,
child: Padding(
padding: EdgeInsets.all(5.0),
child: FlatButton(
color: pressed ? Colors.blue : Colors.red,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
splashColor: Colors.blueAccent,
child: Text("I am a button"),
onPressed: () {
setState(() => { pressed = !pressed });
// call the callback that was passed in from the parent widget
widget.onPressed();
},
),
)
);
}
}
无论您使用什么 UI 框架(angular、vue、flutter、react),我都发现 lifting state up by react 非常有用。
把状态放在你需要的地方,并且只放在你需要的地方。