Search code examples
flutterdartdrop-down-menuoverlaystatefulwidget

change variable value of other instances in flutter


I try to create custom dropdown for my app. And the dropdown can have three duplicate on the same screen. When each dropdown tapped, there is a variable called isDropdownOpened set to true. The case, when one of the dropdown opened then I wan't the others have to set it's isDropdownOpened variable to false again. So, how to change the isDropdownOpened value automatically when other instances of dropdown tapped?

should i use state management like provider, or bloc and cubit? Or even i can do it with setState.

here is the code.

class SearchDropdownButton extends StatefulWidget {
  const SearchDropdownButton({
    Key? key,
    required this.text,
  }) : super(key: key);

  final String text;

  @override
  State<SearchDropdownButton> createState() => _SearchDropdownButtonState();
}

class _SearchDropdownButtonState extends State<SearchDropdownButton> {
  late OverlayEntry _categoryBottomBar;
  bool isDropdownOpened = false;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            if (isDropdownOpened) {
              _categoryBottomBar.remove();
            } else {
              Overlay.of(context)!.insert(_categoryBottomBar);
            }

            isDropdownOpened = !isDropdownOpened;
          });
        },

and the instances on a row.

Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: const [
    SizedBox(width: 20),
    SearchDropdownButton(text: "Consume"),
    SizedBox(width: 20),
    SearchDropdownButton(text: "Gadget"),
    SizedBox(width: 20),
    SearchDropdownButton(text: "Fashion"),
    SizedBox(width: 20),
  ],
),

the complete code : https://pastebin.com/QtfDfXzU


Solution

  • Your case is not specific to flutter (React is same). Basic way to do this is moving isDropdownOpened state to parent stateful widget. Corresponding react tutorial is here.

    If you want to do this in implicit way then yes, you should use state management library for inter-component state sharing.