简体   繁体   中英

How to dismiss/close PopupMenuButton when using ValueListenableBuilder

I need to use RadioListTile in PopupMenuButton , but the default implementation of PopupMenuButton doesn't allow it because PopupMenuButton has its onSelected method and Radio class have its onChanged method so they are managing their own state if I use Radio class onChanged method then it doesn't dismiss/close PopupMenuButton which default behaviour when I use its onSelected method and it doesn't update radio buttons so for that I am using a workaround described here but with some modifications, I am using ValueListenableBuilder instead of AnimatedBuilder but the problem is that I want to its default behaviour of auto dismiss/closing when I select an item which is not from onSelected now.

here is the minimal sample

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!;
              },
            ),
          ),
        ),
      ),
    );
  }
}

solution for this just use Navigator.pop(context); for any dialog, popup menu, or screen to go back or removed from screen i used it like this

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

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