How to check whether a flutter DropdownButton is currently open or closed?

43 Views Asked by At

I am trying to write a flutter application where I need to know whether a DropdownButton is currently opened and displaying all of the options or not.

On the official flutter github page there is an issue where developers say that the selectedItemBuilder option should be able to carry out the functionality of the callback of the button being opened or closed, but after going to the page they linked I simply could not figure out how to achieve the functionality. The function is not even called if I close the dropdown by pressing outside of it.

Does anyone know how this can be achieved?

1

There are 1 best solutions below

1
Dharam Budh On

Try this:

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedValue;
  final FocusNode focusNode = FocusNode();
  bool isDropDownOpened = false;

  @override
  void initState() {
    super.initState();
    focusNode.addListener(functionCheckFocus);
  }

  @override
  void dispose() {
    focusNode.removeListener(functionCheckFocus);
    super.dispose();
  }

  void functionCheckFocus() {
    isDropDownOpened = !focusNode.hasFocus;
    print("isDropDownOpened: $isDropDownOpened");
    return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: DropdownButton<String>(
          value: selectedValue,
          focusNode: focusNode,
          items: <String>['A', 'B', 'C', 'D'].map(
            (String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            },
          ).toList(),
          onChanged: (value) {
            selectedValue = value;
            setState(() {});
          },
        ),
      ),
    );
  }
}