1.自定义Widget状态
class TapboxA extends StatefulWidget { TapboxA({Key key}) : super(key: key); @override State createState() => _TapboxAState(); } class _TapboxAState extends State { bool _active = false; //2.在_handleTap中触发setState方法,重新绘制Widget void _handleTap() { setState(() { _active = !_active; }); } @override Widget build(BuildContext context) { return GestureDetector( //1.点击之后触发Widget的onTap事件,在onTap中执行_handleTap方法 onTap: _handleTap, child: Container( width: 200, height: 200, decoration: BoxDecoration( color: _active ? Colors.lightGreen[700] : Colors.green[600], ), child: Text( _active ? "active" : "Inactive", style: TextStyle( fontSize: 32, color: Colors.white, ), ), ), ); } }
1、点击之后触发GestureDetector中的onTap方法,在此方法中执行_handleTap;
2、_handleTap方法执行setState触发Widget重绘。