skip to Main Content

I have an list of string in List. But I want to count it and display it in the text. How can I achieve that?

         StreamBuilder<DocumentSnapshot?>(
                  stream: FirebaseFirestore.instance
                      .collection("groups")
                      .doc(groupId)
                      .snapshots(),
                  builder: (context, snapshot) {
                   //Get a snapShot
                    var countRoom = snapshot.data?['room'];
                    //Display a counted room
                    return Text(countRoom)
                   )
                 }

enter image description here

2

Answers


  1. I want to count it (the list)

    If I correctly understand your question, you need to use the length property as follows:

    var countRoom = snapshot.data?['room'];
    var countRoomLength = countRoom.length;
    

    If you want to count the unique elements in the List, see this SO answer.

    Login or Signup to reply.
  2. If you want sum of the string in your list you can do this:

    var rooms = snapshot.data?['room'];
    int countRoom = rooms.fold(0, (int previousValue, element) => previousValue + int.parse(element));
    
    return Text("$countRoom")//show 2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search