Home > Mobile >  how to get the child string from the dropdown menu item in flutter
how to get the child string from the dropdown menu item in flutter

Time:08-21

I am new in flutter...

I need to get the String inside the text field in Dropdown menu button while onChange function called... here is my code below...

BlocBuilder<MemberBloc, MemberState>(builder: (context, state) {
            if (state.hasError) {
              return const Text('error');
            } else if (state.isLoading) {
              return const CircularProgressIndicator(
                strokeWidth: 2,
              );
            } else {
              final _data = state.membersList;
              ValueNotifier<String> dropdownvalue =
                  ValueNotifier(_data[0].memberId);
              accountId = _data[0].memberId;
              log(accountId);
              return ValueListenableBuilder(
                  valueListenable: dropdownvalue,
                  builder: (BuildContext context, String vale, Widget? _) {
                    return DropdownButton(
                        menuMaxHeight: 300,
                        value: dropdownvalue.value,
                        onChanged: (String? value) {
                          value != null
                              ? dropdownvalue.value = value
                              : dropdownvalue;
                          accountId = value!;
                        },
                        items: _data.map((e) {
                          return DropdownMenuItem(
                            child: Text(e.name),
                            value: e.memberId,
                          );
                        }).toList());
                  });
            }
          })

I need to save e.name value into a variable when on onchange function called

CodePudding user response:

You can directly listen to model class and also use on DropdownButton<ModelClass> instead of string.

  final dropdownvalue = ValueNotifier<Item?>(null);
 ValueListenableBuilder<Item?>(
  valueListenable: dropdownvalue,
  builder: (BuildContext context, Item? vale, Widget? _) {
    return DropdownButton<Item>(
        menuMaxHeight: 300,
        value: dropdownvalue.value,
        onChanged: (Item? value) {
          value != null
              ? dropdownvalue.value = value
              : dropdownvalue;      
        },

Now you can directly access all the property of your model class. DropdownButton always has not be a string type.

More about DropdownButton

  • Related