Search code examples
flutterdropdownbox

How to print the selected item in a searchable dropdown box (from dropdown_search 5.0.3 package)?


I have a searchable dropdown box, from the package dropdown_search 5.0.3, where the choices in the dropdown box are titles mapped from a list I have created. When an option in the dropdown box is selected, I want to print the title and the corresponding 'amount' value of the option (from the list). However, I am having difficulty extracting the value of the dropdown box. I tried copying the code from some related questions that have been asked on here, but I'm getting the error 'The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(List< String >)?'. Where do I go from here?

Here is my current code:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      theme: ThemeData(),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

typedef ValueChanged<T> = void Function(T value);

class _MyHomePageState extends State<MyHomePage> {
  final _popupBuilderKey = GlobalKey<DropdownSearchState<String>>();
  String dropdownSelected = '';
  final List<Food> foodListData = [
    Food(
      title: 'Food 1',
      id: 1,
      amount: 3,
      date: DateTime.now(),
    ),
    Food(
      title: "Food 2",
      id: 2,
      amount: 1,
      date: DateTime.now(),
    ),
    Food(
      title: 'Food 3',
      id: 3,
      amount: 3,
      date: DateTime.now(),
    ),
    Food(
      title: 'Food 4',
      id: 4,
      amount: 1,
      date: DateTime.now(),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final isLandscape =
        MediaQuery.of(context).orientation == Orientation.landscape;
    AppBar(
      title: const Text(
        'My App',
      ),
    );
    final pageBody = SafeArea(
      child: SingleChildScrollView(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Column(children: <Widget>[
            Text(
              'My Foods',
            ),
            GestureDetector(
              child: ElevatedButton(
                child: Text("Add Food"),
                onPressed: null,
              ),
            ),
            DropdownSearch<String>.multiSelection(
                key: _popupBuilderKey,
                items: foodListData.map((item) {
                  return (item.title).toString();
                }).toList(),
                popupProps: PopupPropsMultiSelection.menu(
                  showSelectedItems: true,
                  showSearchBox: true,
                ),
                onChanged: (String selectedValue) {
               dropdownSelected =  selectedValue;
                }
                )
          ])
        ],
      )),
    );

    return Scaffold(
      body: pageBody,
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: Platform.isIOS
          ? Container()
          : FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: null,
            ),
    );
  }
}


Solution

  • The multiSelection method returns a list of selected items and not a string. While, user may select multiple selections based on the search results that you need to take care of.

    While this solution will assign the first selected value from the DropDown search result to the dropdownSelected variable.

    change:

    onChanged: (String selectedValue) {
                    dropdownSelected = selectedValue;
                  }
    

    to:

     onChanged: (List<String> selectedValue) {
                      dropdownSelected =
                          selectedValue.isNotEmpty ? selectedValue[0] : '';
                    }