首页 > 解决方案 > 将数据从 Firestore 检索到 DropdownButtonFormField 作为初始值,以便对其进行更新

问题描述

我有 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});
                    });
                  },
                ),

如您所见,我将存储的用户名签名为初始值。然后,在用户更改它之后,它在提交字段后在 Firestore 中更新。

这是我想做的地方:

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是一个简单List<String>的选项。

标签: fluttergoogle-cloud-firestoredropdown

解决方案


initState() 使用 dropDownValue = dataFromFireBase; 并将DropdownButtonFormField值设置为 dropDownValue

这是一个例子:

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

您的下拉菜单:

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'],
          ),

有关更多信息,您还可以参考讨论过类似问题的stackoverflow 案例,希望这个答案对您有所帮助。


推荐阅读