文章目录[隐藏]
一、定义子Widget
class TapboxB extends StatelessWidget {
final bool active;
//3.父级Widget传递过来的回调参数
final ValueChanged onChangedListener;
TapboxB({Key key, this.active: false, @required this.onChangedListener})
: super(key: key);
void _handleTap() {
//2._handleTap方法中触发父级Widget传来的回调
onChangedListener(!active);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
//1.点击子Widget触发onTap事件,执行_handleTap方法
onTap: _handleTap,
child: Container(
width: 200,
height: 200,
child: Text(
active ? "active" : "InActive",
style: TextStyle(
fontSize: 32,
color: Colors.white,
),
),
decoration: BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}

1、当点击事件发生时触发子Widget的onTap事件,然后onTap事件中执行子Widget中定义的_handleTap方法;
2、_handleTap方法中的onChangedListener执行回调;
3、onChangedListener父级Widget传递过来的回调参数。
二、定义父Widget
class ParentWidget extends StatefulWidget {
@override
State createState() {
return _ParentWidgetState();
}
}
class _ParentWidgetState extends State {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
//2.setState方法刷新Widget重绘
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return Container(
child: TapboxB(
//1.在初始化子Widget时,传递的参数_handleTapboxChanged触发父级的setState重绘Widget
active: _active,
onChangedListener: _handleTapboxChanged,
),
);
}
}
1、在初始化子Widget时,传递的参数_handleTapboxChanged触发父级的setState重绘Widget;
2、setState方法刷新Widget重绘。