Firestore - Save Query Result

0

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 to show them later in a Text widget.

This is the function i made :

 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(doc["first_name"]);
    }),
    });

  }

How do I save the Username and Score of all 7 users to reuse it later?

This is the Page Code :

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;
  var Nick = "";

  @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) {
        setState(() {
          Nick = (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("Test",
                              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("Punti",
                                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("Test",
                              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("Punti",
                                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(Nick,
                              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("Punti",
                                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}
firebase
flutter
google-cloud-firestore
flutter-layout
asked on Stack Overflow Jan 14, 2021 by Matteo Grondona • edited Jan 14, 2021 by Matteo Grondona

1 Answer

1

The simplest way is use setState.

var firstName = "";

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(() {
             firstName = (doc["first_name"]);                                    
          });
        }),
    });
  }

And change NICK HERE to firstName.

  Text("NICK HERE",...),
answered on Stack Overflow Jan 14, 2021 by John Joe

User contributions licensed under CC BY-SA 3.0