skip to Main Content

Following is my code. I’m trying to get all the ‘Babies’ which are in documents:

class _HomePageeState extends State<HomePagee> {
  String t_babies = getCount().toString();
}

Future getCount() async {
  return FirebaseFirestore.instance.collection('Babies').snapshots().length;
}

Instead I get this error: instance of _future<int>

enter image description here

Here is my Database. I expect to get 2 counts:

enter image description here

2

Answers


  1. You need to use await when getting Future values and also you should pass Future and the type Future<int>:

    Future<int> getCount() async {
      return await FirebaseFirestore.instance.collection('Babies').snapshots().length;
    }
    

    and also get the method using await but inside and async function:

    void example() async {  // <---- here the async you need to add to use await
          int babiesLength = await getCount();  // here use await
        }
    
    Login or Signup to reply.
  2. You should use setState to update the string , because the fetch takes time as it involves network.

    String t_babies = '';
    
      Future<void> _getCount() async {
        setState((){
            t_babies = FirebaseFirestore.instance.collection('Babies').snapshots().length.toString();
        });
      }
    
      @override
      void initState() {
        super.initState();
        _getCount();
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search