///_active:控制子Widget中的文字和文字所在区域的颜色,由父Widget管理;
///_highlight:控制的是边框,由子Widget自己管理

//父Widget
class ParentWidgetC extends StatefulWidget {
@override
State createState() {
return _ParentStateC();
}
}
//父Widget的State
class _ParentStateC extends State {
bool _active = false;
//4.由父Widget传递给子Widget回调子Widget的文字,区域颜色状态
void _handleTapboxChanged(bool newValue) {
//5.调用setState重新绘制Widget
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return Container(
child: ChildWidgetC(
//6.父Widget使用子Widget时传递参数
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//子Widget
class ChildWidgetC extends StatefulWidget {
//父Widget管理的State(active)
final bool active;
final ValueChanged onChanged;
//构造方法
ChildWidgetC({Key key, this.active, this.onChanged}) : super(key: key);
@override
State createState() {
return _ChildStateC();
}
}
//子Widget的State
class _ChildStateC extends State {
//自己管理自己的State
bool _highlight = false;
//定义4种状态的方法
//3.回调给父Widget
void _handleTap() {
widget.onChanged(!widget.active);
}
//2.处理子Widget的状态
void _handleTapDown(TapDownDetails details) {
//重新绘制Widget
setState(() {
_highlight = true;
});
}
void _handleTapUp(TapUpDetails details) {
setState(() {
_highlight = false;
});
}
void _handleTapCancel() {
setState(() {
_highlight = false;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
//1.触发各种回调的地方
onTap: _handleTap,
onTapDown: _handleTapDown,
onTapUp: _handleTapUp,
onTapCancel: _handleTapCancel,
child: Container(
child: Center(
child: Text(
widget.active ? "active" : "InActive",
style: TextStyle(
fontSize: 32,
color: Colors.white,
),
),
),
width: 200,
height: 200,
decoration: BoxDecoration(
color: widget.active ? Colors.lightGreen[700] : Colors.grey[600],
border: _highlight
? Border.all(
color: Colors.teal[700],
width: 10,
)
: null),
),
);
}
}
本案例其实完全没必要使用混合管理的方式即可达到,这里使用只是为了示例。