【问题标题】:Converting int data to string returns null - Flutter Firestore [duplicate]将 int 数据转换为字符串返回 null - Flutter Firestore [重复]
【发布时间】:2020-10-19 19:24:14
【问题描述】:

我有一个文本字段,如果其中一个用户输入一个数字,它会以整数形式保存到 Firestore。当我尝试将数据作为字符串返回时,它显示为 null,即使该特定用户有 int 数据。

这是保存数据的代码:


onPressed: () async {
                    try {
                      final String uid = auth.currentUser.uid;
                      FirebaseFirestore.instance
                          .collection('UserNames')
                          .doc(uid)
                          .update({
                        "plastics": int.parse(_plasticController.text),
                      });
                      Navigator.of(context).pop();
                    } catch (e) {}
                  },

这是我将其转换为字符串并尝试显示它的失败尝试:

首先我创造了一个未来:


final firestore = FirebaseFirestore.instance; //
    FirebaseAuth auth = FirebaseAuth.instance;
    Future<String> getPlasticNum() async {
      final CollectionReference users = firestore.collection('UserNames');

      final String uid = auth.currentUser.uid;

      final result = await users.doc(uid).get();

      return result.data()['plastics'];
    }

然后我尝试显示它:


FutureBuilder(
          future: getPlasticNum(),
          builder: (_, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
            return Text(snapshot.data.toString(),
                style: TextStyle(color: Palette.lightGreen, fontSize: 20));
          },
        ),

【问题讨论】:

  • 那么,到目前为止,您所写的内容有什么问题?请编辑问题以解释什么不按您期望的方式工作。如果有错误消息,请将其复制到问题中。我也建议阅读:stackoverflow.com/help/how-to-ask
  • @DougStevenson 我编辑了这个问题,希望能更清楚地说明我尝试将 int 数据作为字符串返回的事实返回 null,即使当前用户有数据。这会让事情变得更容易吗?
  • 您应该添加一些调试日志记录,以确保您从文档中获得了预期的数据。您可能还应该阅读这个问题:stackoverflow.com/questions/54954182/…
  • 如果答案对你有帮助,现在你可以投票 :) stackoverflow.com/a/64434263/10659482
  • @Akif 刚刚成功,再次感谢。

标签: flutter dart google-cloud-firestore


【解决方案1】:
    Future<String> getPlasticNum()

在这里,您尝试获取一个字符串值。所以你需要将你的数据转换为字符串。

  return result.data()['plastics'].toString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 2014-03-23
    • 2012-01-24
    • 2013-11-04
    • 2021-12-25
    相关资源
    最近更新 更多