skip to Main Content

I would like the appBar title of my Scaffold to display the total number of items (length) in a Firebase Query at launch, but it keeps returning Instance of 'Future<int>'. How can I fix this?

Here’s my code:

Query itemList = FirebaseFirestore.instance
      .collection('simple');
      
Future<int> itemCount() async => FirebaseFirestore.instance
      .collection('simple')
      .snapshots()
      .length;
      
...      

    return Scaffold(

            appBar: AppBar(
              title: Text("# Items: " + itemCount().toString()),
              
              // DISPLAYS: # Items: Instance of 'Future<int>'

Unfortunately, it displays Instance of 'Future<int>'. What do I have to change to obtain the item count (length) and have that show-up in the title text?

Thank you!

3

Answers


  1. Chosen as BEST ANSWER

    After some experimenting, I came to the conclusion that I need to use StreamBuilder. Here's the solution that fixed it:

                appBar: AppBar(
                  title: StreamBuilder(
                    stream: itemList.snapshots(),
                    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Text("# Items: ...");
                      }
    
                      else if (snapshot.hasData) {
                        return Text("# Items: ${snapshot.data?.docs.length ?? 0}");
                      }
    
                      else {
                        return const Text('# Items: 0');
                      }
    
                    },  // Item Builder
                  ),  // Stream Builder
                ),  // App Bar
    

    Screenshot of completed project with # Items in appBar title: Screenshot of completed project

    The floating action button adds items to the list and onTap deletes the selected item from the list. The title remains updated.

    I hope this helps someone in the future.


  2. You can use a FutureBuilder like this :

    AppBar(
        title: FutureBuilder<String>(
               future: itemCount(), 
               builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                   if (snapshot.hasData) {
                      return Text("# Items: " + snapshot.data.toString());
                   }else {
                      Text("No data");
                   }
               }),
         )
    
    Login or Signup to reply.
  3. You are calling a "Future" function, thats the function return a Future so you cant display it like that, you need to use an await (if you are in async function) or a .then() (if you’r not in async function).
    The best way to print it in your case is to use a FutureBuilder or the keyword await.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search