Search code examples
flutterdropdownflutter-layoutbottom-sheet

Show bottom sheet with dropwdown options on dropdown click in flutter


I have a DropDown which shows various options. The current behavior displays the options as a DropdownMenuItem.

How can I switch the DropdownMenuItem to a BottomSheet which shows all the options within the DropDown?

Current code:

DropdownButtonHideUnderline(
  child: Container(
    color: Color.fromRGBO(216, 216, 216, 0.33),
    padding: const EdgeInsets.fromLTRB(32, 8, 16, 8),
    child: DropdownButton<String>(
      hint: Text("TEST DROPDOWN"),
      items: <String>['A', 'B', 'C', 'D'].map((String value) {

        // this crashes
        return showModalBottomSheet(context: context, builder: (builder) {
          return Container(
            child: Text('Hello From Modal Bottom Sheet'),
            padding: EdgeInsets.all(40.0),
          );
        });

        // this works
        return new DropdownMenuItem<String>(
          value: value,
          child: new Text(value),
        );

      }).toList(),
      ...

EDIT: I am trying to display something similar to an iOS date selector on dropdown click.


Solution

  • If you want to make your own, here's a simple example made by me:

    class ModalDropDown extends StatefulWidget {
      @override
      _ModalDropDownState createState() => _ModalDropDownState();
    }
    
    class _ModalDropDownState extends State<ModalDropDown> {
      String _selected = '';
      List<String> _items = ['A', 'B', 'C', 'D'];
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text('Show Modal'),
                onPressed: () => showModal(context),
              ),
              Text('Selected item: $_selected')
            ],
          ),
        );
      }
    
      void showModal(context){
        showModalBottomSheet(
          context: context,
          builder: (context){
            return Container(
              padding: EdgeInsets.all(8),
              height: 200,
              alignment: Alignment.center,
              child: ListView.separated(
                itemCount: _items.length,
                separatorBuilder: (context, int) {
                  return Divider();
                },
                itemBuilder: (context, index) {
                  return GestureDetector(
                    child: Text(_items[index]),
                    onTap: () {
                      setState(() {
                        _selected = _items[index];
                      });
                      Navigator.of(context).pop();
                    }
                  );
                }
              ),
            );
          }
        );
      }
    }
    

    If instead you want the Flutter made picker for iOS, you can use the CupertinoPicker