skip to Main Content

I’m a bit inexperienced with Firebase data output I have a query in firestore for a data counter in a collection it looks like this (taken and slightly corrected from the official documentation)

final fs = FirebaseFirestore.instance;
fs.collection("users").count().get().then((users) => print('${users.count}'),
);

Help with its output in Text() Classical output of specific data from a collection is clear to me, but here any attempt leads me into a stupor, I am not a very strong expert in Flutter and would like to see a small example of how I can implement it

2

Answers


  1. Chosen as BEST ANSWER

    Anyway, what worked for me was

        final fs = FirebaseFirestore.instance;
        final Future<AggregateQuerySnapshot> documents =
            FirebaseFirestore.instance.collection('users').count().get();
    
    
    FutureBuilder<AggregateQuerySnapshot>(
                  future: documents,
                  builder: (BuildContext context, AsyncSnapshot<AggregateQuerySnapshot> snapshot) {
                    late Text text;
                    if (snapshot.hasData) {
                      text = Text('Total Users: ${snapshot.data!.count.toString()}',
                          style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                              color: appColorYellow));
                    } else if (snapshot.hasError) {
                      text = Text("Error");
                    } else {
                      text = Text("Loading");
                    }
                    return Center(child: text);
                  },
                ),
    

  2. you can use Future Builder :
    https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    final fs = FirebaseFirestore.instance;
    final future = await fs.collection("users").count().get(); 
      @override
      Widget build(BuildContext context) {
        return DefaultTextStyle(
          style: Theme.of(context).textTheme.displayMedium!,
          textAlign: TextAlign.center,
          child: FutureBuilder<String>(
            future: future, 
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
             late Text text;
              if (snapshot.hasData) {
                 text = Text(snapshot.data.count.toString()) ; 
              } else if (snapshot.hasError) {
                text = Text("Error"); 
              } else {
                text = Text("Loading"):
              }
              return Center(
                child: text
              );
            },
          ),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search