fluttermobile

How to implement dropdownbutton into a function in flutter


Im working on a company project. But I can't simply get the idea of how to implement a basic dropdown button into a function but I can't seem to make the values change in the dropdown function what do you think im doing wrong here's my code:

Widget buildDropdownField({
  required String dropdownHeader,
  required String dropdownValue,
}) {
  return Column(
    children: <Widget>[
      Text(dropdownHeader),
      const SizedBox(
        height: 10,
      ),
      //dropdownField
      DropdownButton<String>(
        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        elevation: 16,
        style: const TextStyle(color: Colors.deepPurple),
        underline: Container(
          height: 2,
          color: Colors.deepPurpleAccent,
        ),
        onChanged: (String? newValue) {
          setState(() {
            dropdownValue = newValue!;
          });
        },
        items: <String>['-', 'Geçti', 'Kaldı', 'Belirsiz']
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      )
    ],
  );
}

Solution

  • Wrap with StatefulBuilder it will work.

    Widget buildDropdownField(
          {required String dropdownHeader, required String dropdownValue}) {
        return Column(
          children: <Widget>[
            Text(dropdownHeader),
            const SizedBox(
              height: 10,
            ),
            StatefulBuilder(
              builder: (_, setDropState) {
                return DropdownButton<String>(
                  value: dropdownValue,
                  icon: const Icon(Icons.arrow_downward),
                  elevation: 16,
                  style: const TextStyle(color: Colors.deepPurple),
                  underline: Container(
                    height: 2,
                    color: Colors.deepPurpleAccent,
                  ),
                  onChanged: (String? newValue) {
                    setDropState(() {
                      dropdownValue = newValue!;
                    });
                  },
                  items: <String>['-', 'Geçti', 'Kaldı', 'Belirsiz']
                      .map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                );
              },
            )
          ],
        );
      }