You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Firestore获取文档ID列表并在DropdownButton中使用

从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:10:25