Home > OS >  Flutter : Dropdown reusability
Flutter : Dropdown reusability

Time:09-20

I need to reuse a dropdown widget, So I created a method. I am calling like this :

buildDropDown("Blood Group", bloodGroups, _groupSelected),

The method definition:

DropdownButtonFormField2<String> buildDropDown(
    String label,
    List<String> items,
    String? selectedElement,
  ) {
    return DropdownButtonFormField2(
      items: items.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: selectedElement,
      onChanged: (value) {
        if (value != null) {
          setState(() {
            selectedElement = value.toString();
          });
        }
        log(selectedElement); // correct value
        log(_groupSelected); // null; though I am giving _groupSelected as selectedElement
      },
      
      hint: Text(label),
    );
  }

So I assumed it is due to pass-by-value, and decided to give a function as argument to change the variable. But I don't know how, because :

() => selectedElement = value.toString(); // "value" only available in the onChange:

I tried creating a widget but it is not working as desired

code:

class DropDownWidget extends StatefulWidget {
  DropDownWidget(
      {Key? key,
      required this.selectedElement,
      required this.label,
      required this.elements})
      : super(key: key);

  String? selectedElement;
  String label;
  List<String> elements;

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget> {
  @override
  Widget build(BuildContext context) {
    return DropdownButtonFormField2(
      items: widget.elements.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: widget.selectedElement,
      onChanged: (value) {
        if (value != null) {
          setState(() => widget.selectedElement = value.toString());
        }
      },
      hint: Text(widget.label),
    );
  }
}

How can I reuse the DropDown?

CodePudding user response:

Try pass the function to it:

DropdownButtonFormField2<String> buildDropDown(String label,
      List<String> items, String? selectedElement, Function(String) onChanged) {
    return DropdownButtonFormField2(
      items: items.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: selectedElement,
      onChanged: onChanged,
      hint: Text(label),
    );
  }

then us it like this :

buildDropDown(
   "Blood Group",
   bloodGroups,
   (value) {
        if (value != null) {
          setState(() {
            _groupSelected = value.toString();
          });
        },
   }
 )
  • Related