首页 > 解决方案 > 如何阻止我的代码将firestore int数据转换为flutter中的字符串

问题描述

我设置了两个集合,一个用于个人用户,一个用于用户可以加入的组。在单个集合中,用户有一个称为塑料的 int 数据,但是当我尝试将该 int 数据分组显示时,它会在 Firestore 中转换为字符串。这很糟糕,因为我需要这些数据保持整数,因为用户可以添加到它,因此当它变成一个字符串时,用户不能再更新组集合中的该值,仅针对他们的个人集合。

这是个人用户收藏的照片:

在此处输入图像描述

如您所见,称为塑料的 int 数据保存为 int。

现在,这是该组的收藏照片,它使用相同的信息,但塑料被保存为字符串而不是 int。

在此处输入图像描述

这里我认为可能导致 int 变成字符串的代码。

@override
  Widget build(BuildContext context) {
    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'].toString();
    }

这个未来仅适用于个人用户,以便他们的 int 数据转换为字符串,以便我可以将其显示为文本。

当我尝试再次为组获取他们的 int 数据时:

@override
  Widget build(BuildContext context) {
    final CollectionReference users = firestore.collection('UserNames');

    final String uid = auth.currentUser.uid;

    return FutureBuilder(
        future: users.doc(uid).get(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final result = snapshot.data;
            final groupId = result.data()['groupId'];
            return FutureBuilder<QuerySnapshot>(
                // <2> Pass `Future<QuerySnapshot>` to future
                future: FirebaseFirestore.instance
                    .collection('Groups')
                    .doc(groupId)
                    .collection('Members')
                    .orderBy('plastics', descending: true)
                    .get(), //Once the async problem is solved i will be able to save the groupId as. variable to be used in my doc path to access this collection.  How do I do this?
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // <3> Retrieve `List<DocumentSnapshot>` from snapshot
                    final List<DocumentSnapshot> documents = snapshot.data.docs;
                    return ListView(
                        children: documents
                            .map((doc) => Card(
                                  child: ListTile(
                                    title: Text(doc['displayName']),
                                    subtitle: Text(doc['plastics']),
                                  ),
                                ))
                            .toList());
                  } else if (snapshot.hasError) {
                    return Text('Its Error!');
                  }
                });
          }
        });
  }

这将 Firestore 中的 int 数据显示为字符串。

我不明白为什么即使我从另一个集合中获取相同的数据,它也会变成一个字符串,因为在单个集合中它被保存为一个 int?

标签: fluttergoogle-cloud-firestore

解决方案


在 firestore 中,数据存储为字符串,您不能在 firestore 中将数据存储为 int 。如果你想要 int 值,那么你可以使用在代码中手动转换它

  int.parse('string')

推荐阅读