簡體   English   中英

如何獲取 Firestore 上另一個集合內的集合內的所有文檔?

[英]How to get all documents that are inside of a collection that is inside of another collection on Firestore?

好吧,我正在嘗試構建一個功能,當我單擊最喜歡的圖標時,我會選擇一個地方作為我最喜歡的地方之一。 如果我想查看我最喜歡的地方,我只需轉到應返回所有我最喜歡的地方的最喜歡的頁面。 我有兩個最喜歡的地方存放在我的 Firestore 上。 當我試圖獲取它們時,什么都不返回......這就是問題所在。

每個最喜歡的文檔都包含城市、圖像等字段。這是我的數據庫: https : //i.imgur.com/CmTr4vG.png

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Favorites extends StatefulWidget {
  @override
  _FavoritesState createState() => _FavoritesState();
}

class _FavoritesState extends State<Favorites> {
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    dynamic loadFavorites() async{
      final FirebaseUser user = await FirebaseAuth.instance.currentUser();
      final dynamic userUid = user.uid;
      return userUid;
    }

    dynamic document = loadFavorites();

    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(top: 30.0, bottom: 5.0),
              child: Text("Favoritos", 
              style: TextStyle(fontSize: 20),
              textAlign: TextAlign.center, 
              ),
            ),
            Container(
              child: FutureBuilder<QuerySnapshot>(
                future: Firestore.instance.collection("users").document(document.toString()).collection("favorites").getDocuments(),
                builder: (context, snapshot){
                  if(!snapshot.hasData){
                    return Center(child: CircularProgressIndicator());
                  }else{
                    return snapshot.data.documents.isEmpty ? Center(child: Text("Nenhum favorito escolhido.")) : ListView.builder(
                      physics: const NeverScrollableScrollPhysics(),
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshot.data.documents.length,
                      itemBuilder: (context, index){
                        return Container(
                          padding: EdgeInsets.all(10.0),
                          child: buildFavorite(width, height, snapshot.data.documents[index]),
                        );

                      },
                    );
                  }
                },
              ),
            ),

          ],  
        ),
      ),     
    );   
  }
  Widget buildFavorite(double width, double height, DocumentSnapshot document){
    return Container(
      padding: EdgeInsets.all(10.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: Colors.grey,
            offset: Offset(1.0, 1.0),
            blurRadius: 10.0,
          ),
        ],
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Stack(
        children: <Widget>[
          //Padding(padding: EdgeInsets.only(top: 100),),
          Container(
            margin: EdgeInsets.only(bottom: 20.0, left: 20.0),
            child: Text(document["title"], style: TextStyle(fontSize: 18),),
          ),

          Container(
            width: width * 0.37,
            height: height * 0.18,
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              image: DecorationImage(
                fit: BoxFit.fill,
                image: NetworkImage(document["image"]),
              ),
              boxShadow: <BoxShadow>[
                BoxShadow(
                  color: Colors.grey,
                  offset: Offset(1.0, 1.0),
                  blurRadius: 1.0,
                ),
              ],
            ),
            margin: EdgeInsets.only(left: width * 0.60),
          ),
          Row(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 30.0),
                child: Icon(Icons.location_on, color: Colors.red,),

              ),
              Container(
                margin: EdgeInsets.only(left: 10.0, top: 30.0),
                child: Text(document["text"]),
              ),

            ],
          ),
          Row(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 60.0),
                child: Icon(Icons.phone, color: Colors.red),

              ),
              Container(
                margin: EdgeInsets.only(left: 10.0, top: 60.0),
                child: Text(document["phone"]),
              ),
            ],
          ),
          Row(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 90.0),
                child: Icon(Icons.timer, color: Colors.red,),
              ),
              Container(
                margin: EdgeInsets.only(left: 10.0, top: 90.0),
                child: Text(document["time"]),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

你的問題在這里:

future: Firestore.instance.collection("users").document(document.toString()).collection("favorites").getDocuments(),

document.toString()將返回Instance of Future<dynamic>因為這個變量的實際類型是你的loadUser()函數的返回類型,它是Future<dynamic>並且對象的toString()方法通常Instance of CLASS_NAME 通常,我強烈建議您通過始終使用顯式類型而不是動態類型來利用 dart 的類型安全性! 使用類型時發生的錯誤表明您正在嘗試的內容不正確,這有助於更好地了解預期的值類型。

您正在嘗試檢索userUid以在您的FutureBuilder使用它,但不幸的是,此函數需要async因為您必須從 Firebase 獲取它。 周圍的功能( build您的Widget )不是異步的。 因此,您無法按照您的意願解析loadUser()函數。 要解決此問題,您需要在build函數之外提取userUid和收藏夾檢索 - 讓我向您展示一個示例:

Future<QuerySnapshot> getFavoritesFromUser() async {
  FirebaseUser user = await FirebaseAuth.instance.currentUser();
  final String userUid = user.uid;
  
  return Firestore.instance.collection("users").document(userUid).collection("favorites").getDocuments();
}

@override
Widget build(BuildContext context) {
  ...
  Container(
    child: FutureBuilder<QuerySnapshot>(
      future: this.getFavoritesFromUser()
      ...
  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM