How to save DropdownButtonFormField value to Firebase real-time database?

Viewed 20

I'm using firebase real-time database and I have a form where the user adds the information to the database using it, but I'm stuck with the DropdownButtonFormField, how can I store the value in my database when the form button is pressed? I used to use the controller when it was TextFormField, but now, I don't know what to do

DropdownButtonFormField(
                          decoration: InputDecoration(
                              enabledBorder: OutlineInputBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(20.0)),
                                borderSide:
                                    BorderSide(width: 2, color: appColor),
                              ),
                              labelText: 'Location',
                              labelStyle: TextStyle(
                                  fontSize: 20, color: Colors.black)),
                          isExpanded: true,
                          // Initial Value
                          value: selectedLocation,
                          icon: const Icon(
                            Icons.keyboard_arrow_down,
                            color: appColor,
                          ),
                          // Array list of items
                          items: Locations.map((String items) {
                            return DropdownMenuItem(
                              value: items,
                              child: Text(items),
                            );
                          }).toList(),
                          // After selecting the desired option,it will
                          // change button value to selected value
                          onChanged: (String? newLocation) {
                            setState(() {
                              selectedLocation = newLocation!;
                            });
                          },
                        ),
1 Answers

you get the selectedLocation value and pass that to firebase method. print selectedLocation in the onChange method then when ever you click item in dropdown, the selectedLocation will change.

DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");

await ref.set({
  "selectedLocation": selectedLocation ,
});
Related