Home > Back-end >  Flutter | FireStore - logic with if / else statement in Future or FutureBuilder
Flutter | FireStore - logic with if / else statement in Future or FutureBuilder

Time:07-13

I'm able to count the documents in a collection with the below snippet, and it works well. However, I would also like to have an if/else statement based on the count and perform some further actions. For example if the return of the Future/FutureBuilder is odd then perform 'action x' and if it's an even number of documents then perform 'action y'

How would you add this logic into a Future or FutureBuilder? I tried also

var xxx = data.then((value) => value); and then to say if (value > 0) {}, but this would give an error:

The operator '>' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>'. Try defining the operator '>

FutureBuilder<QuerySnapshot<Map<String, dynamic>>> testMethod(_variab) {
    return FutureBuilder(
      future: countCollection(_variab),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text("Something went wrong");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          var docSnapshots = snapshot.data?.docs;

          print(docSnapshots?.length);
          var x = docSnapshots?.length;

          return Text(x.toString());
        }

        return Container(
          alignment: Alignment.topCenter,
          margin: const EdgeInsets.only(top: 20),
          child: const CircularProgressIndicator(
            semanticsLabel: 'Loading data..',
            backgroundColor: Colors.grey,
          ),
        );
      },
    );
  }

  Future<QuerySnapshot<Map<String, dynamic>>> countCollection(uid) async {
    Future<QuerySnapshot<Map<String, dynamic>>> data =
        FirebaseFirestore.instance.collection(uid.toString()).get();
    return data;
  }
}

EDIT 1 - Adds Kaushik's recommendation:

ERROR on line if(docSnapshots?.length % 2 == 0):

The operator '%' can't be unconditionally invoked because the receiver can be 'null'. Try adding a null check to the target ('!')

But even after adding it I get the same error: if(docSnapshots?.length! % 2 == 0)

FutureBuilder<QuerySnapshot<Map<String, dynamic>>> testMethod(_variab) {
    return FutureBuilder(
      future: countCollection(_variab),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text("Something went wrong");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          var docSnapshots = snapshot.data?.docs;

          // Add Kaushik recommendation from here:
          if(docSnapshots?.length % 2 == 0)
          {
              print("length is even");
          }
          else{ print(" length is odd");
          }
          // Until here

          print(docSnapshots?.length);
          var x = docSnapshots?.length;

          return Text(x.toString());
        }

        return Container(
          alignment: Alignment.topCenter,
          margin: const EdgeInsets.only(top: 20),
          child: const CircularProgressIndicator(
            semanticsLabel: 'Loading data..',
            backgroundColor: Colors.grey,
          ),
        );
      },
    );
  }

  Future<QuerySnapshot<Map<String, dynamic>>> countCollection(uid) async {
    Future<QuerySnapshot<Map<String, dynamic>>> data =
        FirebaseFirestore.instance.collection(uid.toString()).get();
    return data;
  }

CodePudding user response:

Since you have the length you can check it with a normal if else

int docLength = docSnapshots?.length ?? 0;
if(docLength % 2 == 0)
{
  print("length is even");
}
else{
  print(" length is odd");
}

If you wish to return different widgets based on the length then you can also do

int docLength = docSnapshots?.length ?? 0;
return (docLength % 2== 0)?Text("even number"): Text("odd number");

Please note this condition will return odd number even if the docSnapshots is null. Please handle that case too.

  • Related