Home > Software design >  Finding the total amount of times a specific value is found within two different arrays in the backe
Finding the total amount of times a specific value is found within two different arrays in the backe

Time:08-01

I'm trying to find the total amount of times a specific value (uid) is found within two different arrays in the firestore database. Retrieving the total amount of occurrences for a single array works without any issues but when I try to render the sum of two different snapshot.data.length instances, I receive this error: type 'Null' is not a subtype of type 'num'

This is the specific line where I get the error:

'${(snapshot1.data as dynamic)?.docs.length ?? 0   (snapshot2.data as dynamic)?.docs.length ?? 0} ',

Any help on how to solve this error would be greatly appreciated!

Full code below:

Container(
  child: StreamBuilder(
    stream: FirebaseFirestore
        .instance
        .collection(
            'posts')
        .where('plus',
            arrayContains:
                _post
                    .uid)
        .snapshots(),
    builder: (content,
        snapshot1) {
      return StreamBuilder(
        stream: FirebaseFirestore
            .instance
            .collection(
                'posts')
            .where(
                'minus',
                arrayContains:
                    _post.uid)
            .snapshots(),
        builder: (content,
            snapshot2) {
          return Row(
            children: [
              Text(
                '${(snapshot1.data as dynamic)?.docs.length ?? 0   (snapshot2.data as dynamic)?.docs.length ?? 0} ',
                style:
                    const TextStyle(
                  color:
                      Colors.black,
                  fontWeight:
                      FontWeight.w500,
                ),
              ),
              
            ],
          );
        },
      );
    },
  ),
),

CodePudding user response:

Parentheses come in handy here :)

Take a look at this code

void main() {
  final someNull = null;
  final otherNull = null;
  // print(someNull ?? 0   otherNull ?? 1);
  print((someNull ?? 0)   (otherNull ?? 1));
}

If you uncomment the first print function, it won't even compile - throws an error exactly like in your case. You have to separate yours operation too --> '${((snapshot1.data as dynamic)?.docs.length ?? 0) ((snapshot2.data as dynamic)?.docs.length ?? 0})'

  • Related