如何从Firestore获取文档ID列表并在DropdownButton中使用
我需要从Firestore集合中获取文档ID列表,以便在DropdownButton中使用,从而选择特定文档。以下代码可以打印集合中每个文档的doc.id:
void getDevices () async { var firebaseUser = FirebaseAuth.instance.currentUser?.email; print('firebaseUser: $firebaseUser'); await firestoreInstance.collection(devices).where('email', isEqualTo: '$firebaseUser').get().then((value) { value.docs.forEach((element) {print(element.id);}); }); }
我需要将每个文档的doc.id存入列表中。
解决方案
1. 修改getDevices方法,返回文档ID列表
将原方法修改为返回包含文档ID的字符串列表的Future:
Future<List<String>> getDevices() async { var firebaseUser = FirebaseAuth.instance.currentUser?.email; var query = await firestoreInstance .collection(devices) .where('email', isEqualTo: '$firebaseUser') .get(); List<String> _documentsIds = query.docs.map((doc) => doc.id).toList(); return _documentsIds; }
2. 结合FutureBuilder实现DropdownButton
通过FutureBuilder异步获取数据并渲染DropdownButton组件:
Container( width: 380, padding: const EdgeInsets.symmetric(horizontal: 24.0), decoration: BoxDecoration( border: Border.all( color: Colors.lightBlueAccent, width: 1.0), borderRadius: kBorderRadius), child: DropdownButtonHideUnderline( child: FutureBuilder<List<String>>( future: getDevices(), builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) { if (!snapshot.hasData) { return const Text( '等待设备加载', ); } else { return DropdownButton<String>( borderRadius: kBorderRadius, iconSize: 40, elevation: 16, hint: const Text( '选择防护设备', ), onChanged: (value) { setState(() { selectedDeviceValue = value!; getDeviceSettings(); }); }, value: selectedDeviceValue, items: snapshot.data ?.map((docId) => DropdownMenuItem<String>( value: docId, child: Text(docId), )) .toList(), ); } })), )
注:优化了代码中的类型声明(将
List<dynamic>改为List<String>),并简化了onChanged中重复的setState调用。
内容的提问来源于stack exchange,提问作者Johan Scheepers
相关产品推荐
相关产品推荐

