Flutter从Firestore QuerySnapshot拉取数据填充DropdownButton问题咨询
错误原因
snapshot.data.docs返回的元素类型为QueryDocumentSnapshot,你直接声明成Map类型接收导致类型不匹配,触发了类型错误。QueryDocumentSnapshot不能直接当做Map读取字段,需要调用data()方法转为Map结构,文档ID可以直接通过id属性获取。
修复后的代码
把你的DropdownButton部分替换为以下代码即可:
return DropdownButton<String>( hint: Text("Select Agency"), value: _currentAgency, // 下拉选择状态更新逻辑,可根据你的业务调整 onChanged: (newValue) { setState(() { _currentAgency = newValue; }); }, items: snapshot.data.docs.map<DropdownMenuItem<String>>((doc) { // doc为QueryDocumentSnapshot类型 String docId = doc.id; // 取文档ID作为value,满足第一个需求 String agencyName = doc.get('name'); // 取name字段作为显示文本,也可替换为doc.data()['name'],满足第二个需求 return DropdownMenuItem<String>( value: docId, child: Text(agencyName), ); }).toList(), );
额外优化建议
你可以给StreamBuilder加上明确的泛型声明,避免后续类型推断错误:
StreamBuilder<QuerySnapshot>( stream: _db.collection('agency').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { // 原有逻辑保持不变 } )
内容的提问来源于stack exchange,提问作者LostTexan
相关产品推荐
相关产品推荐

