父Widget管理子Widget狀態(tài)
在以下示例中,TapboxB通過回調(diào)將其狀態(tài)導(dǎo)出到其父組件,狀態(tài)由父組件管理,因此它的父組件為StatefulWidget。但是由于TapboxB不管理任何狀態(tài),所以TapboxB是StatelessWidget。
ParentWidgetState 類:
- 為TapboxB 管理_active狀態(tài)。
- 實(shí)現(xiàn)_handleTapboxChanged(),當(dāng)盒子被點(diǎn)擊時(shí)調(diào)用的方法。
- 當(dāng)狀態(tài)改變時(shí),調(diào)用setState()更新UI。
TapboxB 類:
- 繼承StatelessWidget類,因?yàn)樗袪顟B(tài)都由其父組件處理。
- 當(dāng)檢測(cè)到點(diǎn)擊時(shí),它會(huì)通知父組件。
// ParentWidget 為 TapboxB 管理狀態(tài).
//------------------------ ParentWidget --------------------------------
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return Container(
child: TapboxB(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//------------------------- TapboxB ----------------------------------
class TapboxB extends StatelessWidget {
TapboxB({Key? key, this.active: false, required this.onChanged})
: super(key: key);
final bool active;
final ValueChanged<bool> onChanged;
void _handleTap() {
onChanged(!active);
}
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
child: Center(
child: Text(
active ? 'Active' : 'Inactive',
style: TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}