繁体   English   中英

使用 ValueListenableBuilder 时如何关闭/关闭 PopupMenuButton

[英]How to dismiss/close PopupMenuButton when using ValueListenableBuilder

我需要使用RadioListTilePopupMenuButton ,但默认实现PopupMenuButton不允许它,因为PopupMenuButton都有onSelected方法和Radio类有它onChanged方法,以便他们管理自己的状态,如果我用RadioonChanged方法,那么它不” t 关闭/关闭PopupMenuButton ,这是我使用onSelected方法时的默认行为,它不更新单选按钮,因此我使用了此处描述的解决方法但经过一些修改,我使用的是ValueListenableBuilder而不是AnimatedBuilder但问题是我当我选择一个现在不是来自onSelected的项目时,想要它的自动关闭/关闭的默认行为。

这是最小的样本

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            actions: [
              SelectionPopupMenu(),
            ],
          ),
        ),
      ),
    );

class SelectionPopupMenu extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _selectionList = [
      'First',
      'Second',
    ];

    final _selectedValueNotifier = ValueNotifier(0);

    return PopupMenuButton<int>(
      onSelected: ,
      itemBuilder: (context) => List.generate(
        _selectionList.length,
        (index) => PopupMenuItem(
          child: ValueListenableBuilder(
            valueListenable: _selectedValueNotifier,
            builder: (context, value, child) => RadioListTile<int>(
              value: index,
              title: Text(_selectionList[index]),
              groupValue: _selectedValueNotifier.value,
              onChanged: (value) {
                _selectedValueNotifier.value = value!;
              },
            ),
          ),
        ),
      ),
    );
  }
}

对此的解决方案只需使用Navigator.pop(context); 对于任何对话框、弹出菜单或屏幕返回或从屏幕中删除,我是这样使用的

 onChanged: (value) {
                  selectedValueNotifier.value = value!;
                  Navigator.pop(context);
                },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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