Mateus Neves
Mateus Neves

Reputation: 764

Retrieve data from Firestore to DropdownButtonFormField as initial value so it can be updated

I have a working code for TextFormField

          TextFormField(
                  decoration: InputDecoration(labelText: 'Full name'),
                  initialValue: output!['full_name'],
                  onFieldSubmitted: (val) {
                    setState(() {
                      newUserName = val;
                      print(val);
                      FirebaseFirestore.instance
                          .collection('users')
                          .doc(widget.userId)
                          .update({'full_name': newUserName});
                    });
                  },
                ),

As you can see, I signed the stored username as the initialValue. Then, after the user changes it, it is update in Firestore after field is submitted.

This is where I want to do it:

DropdownButtonFormField<String>(
decoration: InputDecoration(labelText: 'Select gender'),

validator: (val) => (val == null || val.isEmpty) ? 'Fill the field' : null,
isExpanded: true,
value: _selectedValue,
items: items.map(buildMenuItem).toList(),
onChanged:setState: (val) {
                  setState(() {
                    _selectedValue = val;
                  });
                }),
 )

items is a simple List<String> with the options.

Upvotes: 0

Views: 250

Answers (1)

FadyFouad
FadyFouad

Reputation: 948

in initState() use dropDownValue = dataFromFireBase; and in DropdownButtonFormField set value to dropDownValue

this is an example:

  String dropDownValue ='';
  @override
  void initState() {
    super.initState();
    dropDownValue  = dataFromFireBase;
   }

Your dropDown :

DropdownButtonFormField<String>(
            value: dropDownValue,
            icon: const Icon(Icons.arrow_drop_down),
            iconSize: 24,
            elevation: 16,
            style: const TextStyle(color: Colors.black),
            onChanged: (String? newValue) {
              setState(() {
                dropDownValue  = newValue!;
              });
            },
            items: ['your List'],
          ),

For more information you can also refer to the stackoverflow case where a similar issue has been discussed, I hope this answer is helpful.

Upvotes: 2

Related Questions