Your Location is: Home > Flutter

Cannot save values from Firestore ​in a List

From: Oman View: 1909 Matteo Grondona 

Question

Good evening everyone, I have a problem with Firebase. Basically I'm creating a leaderboard and I have to find the 7 users with the most points, no problem on that one but I can't understand how to save the data of the 7 users into a List to show them later in a Text widget.

The function I created is this :

    Future<void> getLeaderboard() async {
    return await FirebaseFirestore.instance
        .collection("leaderboard")
        .orderBy('Score', descending: true)
        .limit(7)
        .get()
        .then((QuerySnapshot querySnapshot) => {
      querySnapshot.docs.forEach((doc) {
        setState(() {
          LeaderboardPositionList.add(doc["Nick"]);
          LeaderboardPositionList.add(doc["Score"]);
        });
      }),
    });
  }

I created the List : List<String> LeaderboardPositionList;

and I initialized the function

  @override
  void initState() {
    super.initState();
    asyncMethod();
  }

  void asyncMethod() async {
   await getLeaderboard();
  }

and to recall the various nicknames and scores of the 7 users to put them in a text widget I do this:

Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[1],
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'Roboto',
                                  color: const Color(0xFF3A404C),
                                  fontSize: 20.0.sp),
                              textAlign: TextAlign.center,
                            ),

But when I open the page it always remain in loading.

If i do print(doc["Nick]);

The first nickname in the leaderboard is printed.

I also found this "error" in debugging : Tried calling: add("lolc") ...(lolc is one of the nick in the leaderboard).

This is all the code of the page :

import 'package:sizer/sizer.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:goodgoals_android/pages/home_page.dart';
import 'package:goodgoals_android/pages/profile_page.dart';
import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';
import 'package:goodgoals_android/services/authentication.dart';


class soloLeaderboardPage extends StatefulWidget {
  soloLeaderboardPage({Key key, this.auth, this.userId, this.logoutCallback, this.home})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback logoutCallback;
  final String userId;
  final HomePage home;

  @override
  State<StatefulWidget> createState() => new _soloLeaderboardPageState();
}


class _soloLeaderboardPageState extends State<soloLeaderboardPage> {

  final _formKey = new GlobalKey<FormState>();
  final databaseReference = FirebaseFirestore.instance;
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  var _selectedTab = _SelectedTab.leaderboard;

List<String> LeaderboardPositionList = [];

  @override
  void initState() {
    super.initState();
    asyncMethod();
  }

  void asyncMethod() async {
   await getLeaderboard();
  }

  void _handleIndexChanged(int i) {
    setState(() {
      _selectedTab = _SelectedTab.values[i];
      print("Valore $i");
      if (i == 0) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage(),
            ));
      }
      else if (i == 3) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ProfilePage(),
            ));
      }
      else if (i == 2) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => soloLeaderboardPage(),
            ));
      }
    });
  }
  Future<void> getLeaderboard() async {
    return await FirebaseFirestore.instance
        .collection("leaderboard")
        .orderBy('Score', descending: true)
        .limit(7)
        .get()
        .then((QuerySnapshot querySnapshot) => {
      querySnapshot.docs.forEach((doc) {
        print("Done");
        setState(() {
          LeaderboardPositionList.add(doc["Nick"]);
          LeaderboardPositionList.add(doc["Score"]);
        });
      }),
    });
  }



  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      body: Stack(
          children: <Widget>[
            _showForm(),

          ]
      ),
    );
  }

  Widget _showForm() {

    return new Container(
        padding: EdgeInsets.all(10.0),
        child: new Form(
          key: _formKey,
          child: new ListView(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            children: <Widget>[
              leaderbordSelector(),
              showPodium1(),
              showOtherPosition(),
              bottomBarMimic(),
              //bottomBarMimic(),
            ],

          ),
        ));
  }

  Widget bottomBarMimic() {
    return Positioned(
      width: 100.0.w,
      bottom: 0,
      left: 0,
      child: Container(
          color: Colors.white,
          child: SalomonBottomBar(
            currentIndex: _SelectedTab.values.indexOf(_selectedTab),
            onTap: _handleIndexChanged,
            items: [
              SalomonBottomBarItem(
                icon: Icon(Icons.home),
                title: Text("Home"),
                selectedColor: Colors.purple,
              ),
              SalomonBottomBarItem(
                icon: Icon(Icons.menu_book_sharp),
                title: Text("Magazine"),
                selectedColor: Colors.pink,
              ),
              SalomonBottomBarItem(
                icon: Icon(Icons.bar_chart),
                title: Text("Leaderboard"),
                selectedColor: Colors.orange,
              ),
              SalomonBottomBarItem(
                icon: Icon(Icons.person),
                title: Text("Profile"),
                selectedColor: Colors.teal,
              ),
            ],
          )),
    );
  }

  Widget leaderbordSelector() {
    return new Padding(
      padding: EdgeInsets.symmetric(vertical: 5.0.h, horizontal: 17.0.h),
      child: Row(
        children: <Widget>[
          IconButton(
              icon: Icon(Icons.person, color: Colors.blue),
              onPressed: () {}
          ),
          IconButton(
              icon: Icon(Icons.people),
              onPressed: () {}
          ),
        ],
      ),
    );
  }


  Widget showPodium1() {
    return Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Column(
              children: <Widget>[
                Container(
                  height: 20.0.h,
                  width: 30.0.w,
                  decoration: BoxDecoration(
                      color: const Color(0xFFFFFFFF),
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                      border: Border.all(color: Colors.black),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.5),
                          spreadRadius: 2,
                          blurRadius: 7,
                          offset: Offset(0, 3),
                        )
                      ]
                  ),
                  child: Stack(
                      children: <Widget>[
                        Container(
                          width: 80.0.w,
                          height: 10.0.h,
                          decoration: new BoxDecoration(
                              shape: BoxShape.circle,
                              image: new DecorationImage(
                                fit: BoxFit.fitHeight,
                                image: AssetImage('assets/images/no_image.png'),
                              )),
                        ),

                        Container(
                            height: 10.0.h,
                            width: 10.0.w,
                            child:
                            new Image(
                              image: AssetImage(
                                  "assets/images/medal_third.png"),
                            )),

                        Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[0],
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'Roboto',
                                  color: const Color(0xFF3A404C),
                                  fontSize: 20.0.sp),
                              textAlign: TextAlign.center,
                            ),
                            new Align(alignment: Alignment.bottomCenter,
                              child: Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[1],
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Roboto',
                                    color: const Color(0xFF3A404C),
                                    fontSize: 15.0.sp),
                              ),
                            ),

                          ],
                        ),
                      ]),
                )],
            ),

            Column(
              children: <Widget>[
                Container(
                    height: 20.0.h,
                    width: 30.0.w,
                    decoration: BoxDecoration(
                        color: const Color(0xFFFFFFFF),
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        border: Border.all(color: Colors.black),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.5),
                            spreadRadius: 2,
                            blurRadius: 7,
                            offset: Offset(0, 3),
                          )
                        ]
                    ),
                    child: Stack(
                      children: <Widget>[
                        Container(
                          width: 80.0.w,
                          height: 10.0.h,
                          decoration: new BoxDecoration(
                              shape: BoxShape.circle,
                              image: new DecorationImage(
                                fit: BoxFit.fitHeight,
                                image: AssetImage('assets/images/no_image.png'),
                              )),
                        ),
                        Container(
                            height: 10.0.h,
                            width: 10.0.w,
                            child:
                            new Image(
                              image: AssetImage(
                                  "assets/images/medal_first.png"),
                            )),

                        Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[2],
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'Roboto',
                                  color: const Color(0xFF3A404C),
                                  fontSize: 20.0.sp),
                              textAlign: TextAlign.center,
                            ),
                            new Align(alignment: Alignment.bottomCenter,
                              child: Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[3],
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Roboto',
                                    color: const Color(0xFF3A404C),
                                    fontSize: 15.0.sp),
                              ),
                            ),

                          ],
                        ),
                      ],
                    )
                ),
              ],
            ),

            Column(
              children: <Widget>[
                Container(
                    height: 20.0.h,
                    width: 30.0.w,
                    decoration: BoxDecoration(
                        color: const Color(0xFFFFFFFF),
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        border: Border.all(color: Colors.black),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.5),
                            spreadRadius: 2,
                            blurRadius: 7,
                            offset: Offset(0, 3),
                          )
                        ]
                    ),
                    child: Stack(
                      children: <Widget>[
                        Container(
                          width: 80.0.w,
                          height: 10.0.h,
                          decoration: new BoxDecoration(
                              shape: BoxShape.circle,
                              image: new DecorationImage(
                                fit: BoxFit.fitHeight,
                                image: AssetImage('assets/images/no_image.png'),
                              )),
                        ),
                        Container(
                            height: 10.0.h,
                            width: 10.0.w,
                            child:
                            new Image(
                              image: AssetImage(
                                  "assets/images/medal_second.png"),
                            )),

                        Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[4],
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'Roboto',
                                  color: const Color(0xFF3A404C),
                                  fontSize: 20.0.sp),
                              textAlign: TextAlign.center,
                            ),
                            new Align(alignment: Alignment.bottomCenter,
                              child: Text(LeaderboardPositionList == null ?  "Loading..." : LeaderboardPositionList[5],
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Roboto',
                                    color: const Color(0xFF3A404C),
                                    fontSize: 15.0.sp),
                              ),
                            ),

                          ],
                        ),
                      ],
                    )
                ),
              ],
            ),

          ],
        ));
  }


  Widget showOtherPosition() {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 4.0.h),
      elevation: 0,
      color: Colors.transparent,
      child: Padding(
          padding: EdgeInsets.symmetric(vertical: 0.5.h),
          child: Column(
            children: <Widget>[
              Wrap(
                spacing: 5.0,
                children: <Widget>[
                  Container(
                    height: 10.0.h,
                    width: 500.0.w,
                    color: Colors.transparent,
                    child: Container(
                      decoration: BoxDecoration(
                          color: const Color(0xFFFFFFFF),
                          borderRadius: BorderRadius.all(Radius.circular(10.0)),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.5),
                              spreadRadius: 1,
                              blurRadius: 7,
                              offset: Offset(0, 3),
                            )
                          ]
                      ),
                    ),
                  ),
                  SizedBox(height: 20),
                  Container(
                    height: 10.0.h,
                    width: 500.0.w,
                    color: Colors.transparent,
                    child: Container(
                      decoration: BoxDecoration(
                          color: const Color(0xFFFFFFFF),
                          borderRadius: BorderRadius.all(Radius.circular(10.0)),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.5),
                              spreadRadius: 1,
                              blurRadius: 7,
                              offset: Offset(0, 3),
                            )
                          ]
                      ),
                    ),
                  ),
                  SizedBox(height: 20),
                  Container(
                      height: 10.0.h,
                      width: 500.0.w,
                      color: Colors.transparent,
                      child: Container(
                        decoration: BoxDecoration(
                            color: const Color(0xFFFFFFFF),
                            borderRadius: BorderRadius.all(
                                Radius.circular(10.0)),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 1,
                                blurRadius: 7,
                                offset: Offset(0, 3),
                              )
                            ]
                        ),
                      )),
                  SizedBox(height: 20),
                  Container(
                    height: 10.0.h,
                    width: 500.0.w,
                    color: Colors.transparent,
                    child: Container(
                      decoration: BoxDecoration(
                          color: const Color(0xFFFFFFFF),
                          borderRadius: BorderRadius.all(Radius.circular(10.0)),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.5),
                              spreadRadius: 1,
                              blurRadius: 7,
                              offset: Offset(0, 3),
                            )
                          ]
                      ),
                    ),
                  ),

                ],
              )
            ],
          )),
    );
  }

}
enum _SelectedTab {home, magazine, leaderboard, ProfilePage}

Best answer

For all those who have the same problem as me :

Change the List declaration like this : List<String> ListName = [];

And check that all the values ​​in Firesotre are set to String and not to Number.