Flutter Passing Document ID in Firestore Query

3,214

I have realised that the code looks shady on the comment so let me make an answer. What you are trying to do is currently not supported in flutter as can be seen at these GitHub issues 1 and 2.

Change your code to,

class _CategoryState extends State<Category>{
  StreamSubscription<QuerySnapshot> subscription;

  List<DocumentSnapshot> snapshot;

  Query collectionReference;

  void initState() {
    collectionReference = Firestore.instance.collection("mainCategories").document(widget.category).collection("subCategories").orderBy("title");
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        snapshot = datasnapshot.documents;
      });
    });
    super.initState();
  }

...

Hope this helps.

Share:
3,214
Bnd10706
Author by

Bnd10706

Updated on December 15, 2022

Comments

  • Bnd10706
    Bnd10706 over 1 year

    I am trying to figure out how to do this.

    If I pass the document ID hardcoded it works. But Since I have multiple pages, I am trying to figure out how to pass it and then query it..

    My main page has the following.

    import 'package:flutter/material.dart';
    import 'package:onlytag2/pages/category.dart';
    import 'package:onlytag2/widget/maincard.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'dart:async';
    
    class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      StreamSubscription<QuerySnapshot> subscription;
    
      List<DocumentSnapshot> snapshot;
    
      Query collectionReference = Firestore.instance.collection("mainCategories").orderBy("title");
    
      void initState() {
        subscription = collectionReference.snapshots().listen((datasnapshot) {
          setState(() {
            snapshot = datasnapshot.documents;
          });
        });
        super.initState();
      }
    
      @override
      void dispose() {
        subscription.cancel(); //Streams must be closed when not needed
        super.dispose();
      }
    
      passData(DocumentSnapshot snap, String cat, String title) {
        print(cat);
        Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => Category(snapshot: snap, category: cat, title: title,)));
      }
    
      @override
      Widget build(BuildContext context) {
        if (snapshot == null) return Center(
          child: Container(
            color: Colors.black,
            alignment: AlignmentDirectional(0.0, 0.0),
            child: Container(
              color: Colors.black,
              constraints: BoxConstraints(
                  maxHeight: 300.0,
                  maxWidth: 200.0,
                  minWidth: 150.0,
                  minHeight: 150.0
              ),
              child: CircularProgressIndicator(),
            ),
          ),
        );
        return Scaffold(
          backgroundColor: Color(0xff0E0E0F),
          appBar: AppBar(
            centerTitle: true,
            backgroundColor: Colors.black,
            title: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  "#",
                  style: TextStyle(
                      fontSize: 25, color: Color(0xffff9900), fontFamily: 'Dokyo'),
                ),
                Text(
                  "onlytags",
                  style: TextStyle(color: Colors.white, fontFamily: 'Dokyo'),
                )
              ],
            ),
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Column(
                  children: <Widget>[
                    Expanded(
                      child: ListView.builder(
                          itemCount: snapshot.length,
                          itemBuilder: (context, index) {
                            return InkWell(
                              onTap: () => passData(snapshot[index], snapshot[index].documentID.toString(), snapshot[index].data["title"] ),
                              child: MainCard(
                                title: snapshot[index].data["title"],
                                subtitle: snapshot[index].data["subTitle"],
                                image: snapshot[index].data["image"],
                              ),
                            );
                          }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }
    

    The category widget is where I am having the problem.

    Comment Listed where I am having the problem.

    import 'package:flutter/material.dart';
    import 'package:onlytag2/widget/sub.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'dart:async';
    
    class Category extends StatefulWidget {
      DocumentSnapshot snapshot;
      final String category;
      final String title;
    
      Category({this.snapshot, this.category, this.title});
    
      @override
      _CategoryState createState() => _CategoryState();
    }
    
    class _CategoryState extends State<Category>{
      StreamSubscription<QuerySnapshot> subscription;
    
      List<DocumentSnapshot> snapshot;
    
      //How do I get the category passed properly? I know it is the Document ID, but since it changes based on what button is pressed before,
      //I cant figure out how to pass it..
      Query collectionReference = Firestore.instance.collection("mainCategories").document(widget.category).collection("subCategories").orderBy("title");
    
      void initState() {
        subscription = collectionReference.snapshots().listen((datasnapshot) {
          setState(() {
            snapshot = datasnapshot.documents;
          });
        });
        super.initState();
      }
    
    
      @override
      void dispose() {
        subscription.cancel(); //Streams must be closed when not needed
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        if (snapshot == null) return Center(
          child: Container(
            color: Colors.black,
            alignment: AlignmentDirectional(0.0, 0.0),
            child: Container(
              color: Colors.black,
              constraints: BoxConstraints(
                  maxHeight: 300.0,
                  maxWidth: 200.0,
                  minWidth: 150.0,
                  minHeight: 150.0
              ),
              child: CircularProgressIndicator(),
            ),
          ),
        );
        return Scaffold(
          backgroundColor: Color(0xff0E0E0F),
          appBar: AppBar(
            iconTheme: IconThemeData(
              color: Color(0xffff9900),
            ),
            centerTitle: true,
            backgroundColor: Colors.black,
            title: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  "#", style: TextStyle(fontSize: 25, color: Color(0xffff9900), fontFamily: 'Dokyo'),
                ),
                Text(widget.title.toLowerCase(), style: TextStyle(color: Colors.white, fontFamily: 'Dokyo'),)
              ],
            ),
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Column(
                  children: <Widget>[
                    Expanded(
                      child: ListView.builder(
                          itemCount: snapshot.length,
                          itemBuilder: (context, index) {
                            return Sub(
                              title: snapshot[index].data["title"],
                              subtitle: snapshot[index].data["subTitle"],
                              image: snapshot[index].data["image"],
                            );
                          }),
                    ),
                    Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 15),)
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }