flutter - 将数据从 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>
的选项。
解决方案
在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 案例,希望这个答案对您有所帮助。
推荐阅读
- systemd - Systemd 以 status=209/STDOUT 退出
- c# - 如何在 Azure 函数(v2、.net 核心)中注册触发器绑定?
- r - 排列功能:lubridate和dplyr R之间的冲突
- r - 当我的数据未正确对齐时计算 rmse
- java - 单元测试断言与 Mockito.verify()
- xcode - Xcode 语法高亮使文本跳来跳去
- android - 在可扩展列表视图中使用选中的复选框更改项目的位置
- javascript - 如果 Javascript 中的点后所有值都为零,则尾随
- mysql - UPDATE INNER JOIN on 子句中的未知列
- flutter - 如何实现颤动动画