Is there a way to make a dropdownlist inside a TabBar in Flutter?

Issue

I’m trying to add a DropDownList inside a TabBar items so the user can select the dropdown item before the tabbarwiew changes the widget. I tried to make this, but it changes the TabBarView widget before showing the DropDownList items:

tabs: [
          const Tab(
            text: 'Home',
          ),
          const Tab(
            text: 'About us',
          ),
          DropdownButton(
            value: selectedValue,
            items: menuItems, onChanged: (String? value) {
              print(value);
            },
          ),
              

If it’s not possible can you suggest an alternative, please?

Solution

Yes, it is possible to have DropdownButton as Tab.

tabs: takes list of widget and DropdownButton is a widget, you can simply use it.

 String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1,
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('TabBar Widget'),
          bottom: TabBar(
            tabs: <Widget>[
              Tab(
                icon: Icon(Icons.cloud_outlined),
              ),
              Tab(
                icon: Icon(Icons.beach_access_sharp),
              ),
              Tab(
                icon: Icon(Icons.brightness_5_sharp),
              ),
              DropdownButton<String?>(
                value: selectedValue,
                onChanged: (value) {
                  setState(() {
                    selectedValue = value;
                  });
                  print("value");
                },
                items: ["A", "B", "C"]
                    .map(
                      (e) => DropdownMenuItem(
                        child: Text(e),
                        value: e,
                      ),
                    )
                    .toList(),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Center(
              child: Text("It's cloudy here"),
            ),
            Center(
              child: Text("It's rainy here"),
            ),
            Center(
              child: Text("It's sunny here"),
            ),
            Center(
              child: Text("TabBar here ${selectedValue ?? "select 1st"}"),
            ),
          ],
        ),
      ),
    );
  }

Answered By – Yeasin Sheikh

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *