[英]How do you use CheckBoxListTile with PopupMenuButton in Flutter Web?
I don't want to use CheckedPopupMenuItem because my aim is to have a Checkbox for user to interact with.我不想使用 CheckedPopupMenuItem 因为我的目标是有一个复选框供用户交互。 But even calling setState in the CheckBoxListTile in PopupMenuButton it does not rebuild when we tap on it.
但是即使在 PopupMenuButton 的 CheckBoxListTile 中调用 setState,当我们点击它时它也不会重建。
Here is the code:这是代码:
PopupMenuButton(
offset: Offset(100, 100),
elevation: 5.0,
child: _menuIcon,
itemBuilder: (context) => [
PopupMenuItem(
child: CheckBoxListTile(
activeColor: kLeadingOrangeColor,
value: isShow,
onChanged: (value) =>
setState(() => isShow = value),
title: checkboxLabel('Show'),
),
),
],
)
Every time I clicked it, it seems nothing happens although I call setState.每次单击它时,尽管我调用了 setState,但似乎什么也没发生。 So for me to see the change from "checked" mark to "unchecked" mark and vice versa, I had to close and reopen the PopupMenuButton.
因此,为了让我看到从“选中”标记到“未选中”标记的变化,反之亦然,我不得不关闭并重新打开 PopupMenuButton。
After looking high and low for a couple of hours, I found this to be the best solution: (I think this will also work for CheckBox)在高低看了几个小时后,我发现这是最好的解决方案:(我认为这也适用于 CheckBox)
Here is the new code:这是新代码:
PopupMenuButton(
offset: Offset(100, 100),
elevation: 5.0,
child: _menuIcon,
itemBuilder: (context) => [
PopupMenuItem(
child: StatefulBuilder(
builder: (_context, _setState) =>
CheckBoxListTile(
activeColor: kLeadingOrangeColor,
value: isShow,
onChanged: (value) =>
_setState(() => isShow = value),
title: checkboxLabel('Show'),
),
),
),
],
)
Notice that I name the parameters _context and _setState respectively for the StatefulBuilder that wraps around the Checkbox widget.请注意,我分别为围绕 Checkbox 小部件的 StatefulBuilder 命名参数 _context 和 _setState。 This is so that we differentiate the context and setState of this StatefulBuilder with the other StatefulWidgets.
这样我们就可以将这个 StatefulBuilder 的 context 和 setState 与其他 StatefulWidget 区分开来。 And just in case anyone uses something like Blocs, it will use the right context.
以防万一有人使用 Blocs 之类的东西,它将使用正确的上下文。
Consequently, for rebuilding the Checkbox, use the _setState instead of setState.因此,要重建 Checkbox,请使用 _setState 而不是 setState。
Hope this helps someone.希望这可以帮助某人。
If you have a better solution, I'm open for it.如果您有更好的解决方案,我愿意接受。 please feel free to comment below.
请随时在下面发表评论。 Thank you.
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.