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

Flutter如何从函数中获取并打印Map结构的Firebase数据

实现方案

核心问题说明

getData是异步函数,返回的是Future<Map<String, dynamic>>类型,必须等待异步请求执行完成后才能拿到实际的Map数据,不能直接赋值后立即访问字段。

修改后的调用侧代码

你可以将onPressed回调改为异步函数,用await等待执行完成后再操作返回的Map:

class _ProfileCState extends State<ProfileC> {
  // 可以选择存储实际返回的Map,方便后续UI使用
  Map<String, dynamic>? userData;
  Future<Map<String, dynamic>>? dataFuture;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          TextButton(
            onPressed: () async {
              // 等待异步函数执行完成,拿到返回的Map
              final result = await getData();
              // 打印Map中字段示例
              print('姓名:${result["first-name"]} ${result["last-name"]}');
              print('店铺名称:${result["shop-name"]}');
              print('联系电话:${result["phone-number"]}');
              // 如果需要更新UI,调用setState存储数据
              setState(() {
                userData = result;
                dataFuture = Future.value(result);
              });
            },
            child: const Text("test"),
          ),
          // 如果需要在页面上展示数据,可搭配FutureBuilder使用
          if (dataFuture != null)
            FutureBuilder<Map<String, dynamic>>(
              future: dataFuture,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text('店铺地址:${snapshot.data!["location"]}');
                } else if (snapshot.hasError) {
                  return Text('加载失败:${snapshot.error}');
                }
                return const CircularProgressIndicator();
              },
            )
        ],
      ),
    );
  }
}

额外优化建议

你可以对原有getData函数增加异常捕获和空值判断,避免文档不存在、字段缺失导致的崩溃:

Future<Map<String, dynamic>> getData () async {
  Map<String, dynamic> data = {
    "first-name": "",
    "last-name": "",
    "phone-number": "",
    "shop-name": "",
    "work-start": "",
    "work-end": "",
    "location": "",
  };
  try {
    final firestore = FirebaseFirestore.instance;
    final userPersonalData = await firestore.collection("Users").doc("TvIRbwzfrebPj10Cubc0RpnD4Y83").collection("info").doc("personal-dits").get();
    final userShopName = await firestore.collection("Users").doc("TvIRbwzfrebPj10Cubc0RpnD4Y83").collection("info").doc("shop-info").get();
    if (userPersonalData.exists) {
      data["first-name"] = userPersonalData.get("first-name") ?? "";
      data["last-name"] = userPersonalData.get("last-name") ?? "";
    }
    if (userShopName.exists) {
      data["phone-number"] = userShopName.get("Phone number") ?? "";
      data["shop-name"] = userShopName.get("shop name") ?? "";
      data["work-start"] = userShopName.get("work-start") ?? "";
      data["work-end"] = userShopName.get("work-end") ?? "";
      data["location"] = userShopName.get("location") ?? "";
    }
  } catch (e) {
    print("获取数据失败:$e");
  }
  return data;
}

内容的提问来源于stack exchange,提问作者roee attias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:09:01