![](/img/trans.png)
[英]How to change state of one Stateful Widget from another Stateful Widget in Flutter?
[英]Flutter, change Icon state with boolean from one widget to another
我有两个小部件。 首先是 ParticipantScreen(),它在 GridView.builder() 中显示第二个小部件 - ParticipantCard()。 这两个小部件都有麦克风图标,可以让参与者静音。 当我使本地参与者静音时,我单击 ParticipantScreen() 上的麦克风图标,关于这一点,我也想将 ParticipantCard() 中的麦克风图标状态更改为相同的布尔值,但仅适用于列表中用于创建 GridView 的第一项与参与者卡。 是否可以将布尔值从一个小部件传递到另一个小部件?
您可以为此使用回调函数(可以是 typedef)
final Function(bool isMuted) onChanged;
玩这个小部件
class ParentWidget extends StatefulWidget {
const ParentWidget({Key? key}) : super(key: key);
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _isMuted = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Switch(
value: _isMuted,
onChanged: (v) {
setState(() {
_isMuted = !_isMuted;
});
}),
ChildC(
isMuted: _isMuted,
onChanged: (isMuted) {
setState(() {
_isMuted = isMuted;
});
},
),
],
),
);
}
}
class ChildC extends StatefulWidget {
final bool isMuted;
final Function(bool isMuted) onChanged;
const ChildC({
Key? key,
required this.isMuted,
required this.onChanged,
}) : super(key: key);
@override
State<ChildC> createState() => _ChildCState();
}
class _ChildCState extends State<ChildC> {
@override
Widget build(BuildContext context) {
return Switch(
value: widget.isMuted,
onChanged: (v) {
widget.onChanged(v);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.