簡體   English   中英

如何在 Flutter Web 中使用 CheckBoxListTile 和 PopupMenuButton?

[英]How do you use CheckBoxListTile with PopupMenuButton in Flutter Web?

我不想使用 CheckedPopupMenuItem 因為我的目標是有一個復選框供用戶交互。 但是即使在 PopupMenuButton 的 CheckBoxListTile 中調用 setState,當我們點擊它時它也不會重建。

這是代碼:

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'),
             ),
    ),
  ],
)

每次單擊它時,盡管我調用了 setState,但似乎什么也沒發生。 因此,為了讓我看到從“選中”標記到“未選中”標記的變化,反之亦然,我不得不關閉並重新打開 PopupMenuButton。

在高低看了幾個小時后,我發現這是最好的解決方案:(我認為這也適用於 CheckBox)

  1. 將 CheckBoxListTile 包裝在 StatefulBuilder 中
  2. 使用 StatefulBuilder 的 SetState 來重建復選框。

這是新代碼:

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'),
                          ),
             ),
    ),
  ],
)

請注意,我分別為圍繞 Checkbox 小部件的 StatefulBuilder 命名參數 _context 和 _setState。 這樣我們就可以將這個 StatefulBuilder 的 context 和 setState 與其他 StatefulWidget 區分開來。 以防萬一有人使用 Blocs 之類的東西,它將使用正確的上下文。

因此,要重建 Checkbox,請使用 _setState 而不是 setState。

希望這可以幫助某人。

如果您有更好的解決方案,我願意接受。 請隨時在下面發表評論。 謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM