简体   繁体   中英

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. But even calling setState in the CheckBoxListTile in PopupMenuButton it does not rebuild when we tap on it.

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. So for me to see the change from "checked" mark to "unchecked" mark and vice versa, I had to close and reopen the 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)

  1. Wrap the CheckBoxListTile inside a StatefulBuilder
  2. Use that StatefulBuilder's SetState to rebuild the 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. This is so that we differentiate the context and setState of this StatefulBuilder with the other StatefulWidgets. And just in case anyone uses something like Blocs, it will use the right context.

Consequently, for rebuilding the Checkbox, use the _setState instead of setState.

Hope this helps someone.

If you have a better solution, I'm open for it. please feel free to comment below. Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM