簡體   English   中英

可以保留 PopUpMenuButton 的 state 嗎?

[英]It is possible to preserve state of PopUpMenuButton?

在此處輸入圖像描述

目前我正在開發音樂應用程序,根據我的用戶界面,我必須在彈出菜單項中顯示下載、下載進度和下載狀態。但是根據彈出菜單按鈕小部件的行為,它已被處理和卸載。所以當我關閉彈出菜單時項目並再次打開最后一個狀態總是顯示下載而不是下載。因此可以防止關閉后彈出菜單按鈕。

我嘗試了回調函數、provider、getx、auto keep alive 和 stateful builder,但它不起作用。

我正在使用ValueNotifier來保存下載進度。 要保留 state,您可以遵循此結構並使用狀態管理屬性,如 riverpod/bloc

class DTest extends StatefulWidget {
  const DTest({super.key});

  @override
  State<DTest> createState() => _DTestState();
}

class _DTestState extends State<DTest> {
  /// some state-management , also can be add a listener 
  ValueNotifier<double?> downloadProgress = ValueNotifier(null);
  Timer? timer;
  _startDownload() {
    timer ??= Timer.periodic(
      Duration(milliseconds: 10),
      (timer) {
        downloadProgress.value = (downloadProgress.value ?? 0) + .01;
        if (downloadProgress.value! > 1) timer.cancel();
      },
    );
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          PopupMenuButton(
            itemBuilder: (context) {
              return [
                PopupMenuItem(
                  child: ValueListenableBuilder(
                    valueListenable: downloadProgress,
                    builder: (context, value, child) => InkWell(
                        onTap: value == null ? _startDownload : null,
                        child: Text("${value ?? "Download"}")),
                  ),
                )
              ];
            },
          )
        ],
      ),
    );
  }
}

暫無
暫無

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

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