Harshdeep Singh
Harshdeep Singh

Reputation: 1

I want to get the total count of ratings to show average ratings from firestore but I am unable to get the results

Here is my code I want to get the total count of ratings to show average ratings from firestore but I am unable to get the results. please help me get the total of ratings.

Widget reviewPanel(_reviewsStream) {
  return ExpandablePanel(
    header: Transform.scale(scale: 1.5, child: Headings(heading: 'Reviews')),
    collapsed: collapsedReviewList(_reviewsStream),
    expanded: expandedReviewList(_reviewsStream),
  );
}

Widget collapsedReviewList(_reviewsStream) {
  return StreamBuilder<QuerySnapshot>(
      stream: _reviewsStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot2) {
        if (snapshot2.connectionState == ConnectionState.waiting) {
          return Center(
              child: CupertinoActivityIndicator(
            color: Colors.blueGrey.shade900,
            radius: 20,
          ));
        }

        return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: snapshot2.data!.docs.length >= 2
                ? 2
                : snapshot2.data!.docs.length,
            itemBuilder: (context, index) {
              return RepeatedReviewListTile(snapshot2, index);
            });
      });
}

Widget expandedReviewList(_reviewsStream) {
  return StreamBuilder<QuerySnapshot>(
      stream: _reviewsStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot2) {
        if (snapshot2.connectionState == ConnectionState.waiting) {
          return Center(
              child: CupertinoActivityIndicator(
            color: Colors.blueGrey.shade900,
            radius: 20,
          ));
        }
        if (snapshot2.data!.docs.isEmpty) {
          return Center(
            child: Text(
              'This item \n has no Reviews yet!',
              style: TextStyle(
                fontSize: 15,
                letterSpacing: 2,
                fontWeight: FontWeight.w600,
                color: Colors.blueGrey.shade900,
              ),
            ),
          );
        }

        return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: snapshot2.data!.docs.length,
            itemBuilder: (context, index) {
              return RepeatedReviewListTile(snapshot2, index);
            });
      });
}

ListTile RepeatedReviewListTile(
    AsyncSnapshot<QuerySnapshot<Object?>> snapshot2, int index) {
  return ListTile(
    leading: CircleAvatar(
      backgroundColor: Colors.grey,
      child: Icon(
        CupertinoIcons.person,
        color: Colors.white,
      ),
    ),
    title: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(snapshot2.data!.docs[index]['customerName']),
        Row(
          children: [
            Text(snapshot2.data!.docs[index]['starRating'].toString()),
            Icon(
              Icons.star,
              color: Colors.orange,
            )
          ],
        ),
      ],
    ),
    subtitle: Text(
      snapshot2.data!.docs[index]['review'],
    ),
  );
}

enter image description here

enter image description here

I tried for loop, but I don't exactly know how should I implement it.

I am getting an error 'type 'double' is not a subtype of type 'Iterable<dynamic>' '

Upvotes: 0

Views: 101

Answers (1)

Harshdeep Singh
Harshdeep Singh

Reputation: 1

Finally I was able to solve it with the below code and added this fuction in the initState

enter image description here

late final userRef = FirebaseFirestore.instance
      .collection('products')
      .doc(widget.productInfo['productId'])
      .collection('reviews'); 

  num sumRates = 0;
  num ratesLength = 0;
  double averageRate = 0;
  bool isLoading = false;

  getAverageReviews() async {
    setState(() {
      isLoading = true;
    });
    ratesLength = await userRef.get().then((value) => value.docs.length);
    sumRates = await userRef.get().then((value) {
      value.docs.forEach((element) {
        sumRates += element.get('starRating');
      });
      return sumRates;
    });
    averageRate = sumRates / ratesLength;
    setState(() {
      isLoading = false;
    });
  }

Upvotes: 0

Related Questions