Retrieving Data From Firestore in time

强颜欢笑 提交于 2021-01-29 06:47:50

问题


I have looked all over the internet for how to fix this problem and I can't find a solution anywhere. I am using flutter with firestore to make an app. I want to make it so when the user logins into the app at the top shows their name (simple right). I can get data from firestore:


Future<void> getName() async {
  print("Attemping to get name!");
  final firestoreInstance = await FirebaseFirestore.instance;
  FirebaseAuth auth = FirebaseAuth.instance;
  String uid = auth.currentUser.uid.toString();
  await firestoreInstance.collection("Users").doc(uid).get().then((value) {
    print("Name: " + value.data()["firstName"]);
    info.firstName=((value.data()["firstName"]));
  })

class info {
  static String firstName;
}


but it comes in too late so the app just says "Welcome back" As you can see here and not "Welcome back, Connor" As seen here

When I look in the console the function does run but the program doesn't wait for it and continues resulting in a null.

Thanks you

EDIT as requested UI code:


class Home extends StatelessWidget {
  final DatabaseReference = FirebaseDatabase.instance;
  final FirebaseAuth auth = FirebaseAuth.instance;

  static String firstName;
  static String lastName;
  static String email;
  static String companyName;
  static bool isNewAccount = false;
  static String name = "Welcome back";

  Home();

  @override
  Widget build(BuildContext context) {
    final User user = auth.currentUser;
    final uid = user.uid;
    final ref = DatabaseReference.reference();

    if (isNewAccount == true) {
      userSetup(firstName, lastName, email, companyName);
      isNewAccount = false;
    }

    getName(); //does get the name from the database but name will error out as it doesn't get the name fast enough (or that's what I think)
    name= "Welcome back, "+info.firstName;

    return WillPopScope(
      onWillPop: () async => false,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          backgroundColor: Colors.cyan,
          body: SingleChildScrollView(
            child: Container(
              margin:
                  EdgeInsets.only(top: MediaQuery.of(context).size.height / 16),
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: Text(
                      name,
                      textAlign: TextAlign.center,
                      style: new TextStyle(
                        color: Colors.white,
                        fontSize: MediaQuery.of(context).size.width / 16,
                      ),
                    ),
                  ),
                  Container(
                    width: 260,
                    height: 125,
                    child: RaisedButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      child: Text(
                        "CHECK-IN",
                        style: new TextStyle(
                          color: Colors.white,
                          fontSize: 40.0,
                        ),
                      ),
                      color: Colors.grey[850],
                      onPressed: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => Checkin()));
                      },
                    ),
                  ),
                  Container(
                    width: 260,
                    height: 140,
                    padding: EdgeInsets.only(top: 20),
                    child: RaisedButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      child: Text(
                        "CHECK-OUT",
                        style: new TextStyle(
                          color: Colors.white,
                          fontSize: 38.0,
                        ),
                      ),
                      color: Colors.grey[850],
                      onPressed: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => Checkout()));
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 55),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          padding: EdgeInsets.only(right: 20),
                          child: Text(
                            "Sign out: ",
                            style: new TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          child: RaisedButton(
                            child: Text(
                              "SIGN OUT",
                              style: new TextStyle(
                                fontSize: 14.0,
                                color: Colors.white,
                              ),
                            ),
                            color: Colors.grey[700],
                            onPressed: () {
                              context.read<AuthenticationService>().signOut();
                              //return MyApp();
                            },
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          padding: EdgeInsets.only(right: 20),
                          child: Text(
                            "View Stats: ",
                            style: new TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          child: RaisedButton(
                            child: Text(
                              "STATS",
                              style: new TextStyle(
                                fontSize: 14.0,
                                color: Colors.white,
                              ),
                            ),
                            color: Colors.grey[700],
                            onPressed: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => Stats()));
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          padding: EdgeInsets.only(right: 20),
                          child: Text(
                            "View Profile: ",
                            style: new TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          child: RaisedButton(
                            child: Text(
                              "PROFILE",
                              style: new TextStyle(
                                fontSize: 14.0,
                                color: Colors.white,
                              ),
                            ),
                            color: Colors.grey[700],
                            onPressed: () {
                              /*Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => Stats()));*/
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 240,
                    height: 55,
                    margin: EdgeInsets.only(
                        top: MediaQuery.of(context).size.height / 12),
                    child: RaisedButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      child: Text(
                        "EMERGENCY REPORT",
                        style: new TextStyle(
                          color: Colors.white,
                          fontSize: 20.0,
                        ),
                      ),
                      color: Colors.grey[700],
                      onPressed: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => EmergencyReport()));
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  static getAccountDetails(
      String firstName1, String lastName1, String email1, String companyName1) {
    firstName = firstName1;
    lastName = lastName1;
    email = email1;
    companyName = companyName1;
    isNewAccount = true;
  }

  static getFirstName(String nameFirst) {
    name = "Welcome back, "+nameFirst;
  }
}

回答1:


FutureBuilder<DocumentSnapshot>(
          future: firestoreInstance.collection("Users").doc(uid).get(),
          builder: (_,snap){
          return snap.hasData ? Text(snap.data.data()["firstName"]):CircularProgressIndicator();
        },)



回答2:


You need to convert StatelessWidget into StatefullWidget. After that you have to write this in initState method

void initState() {
    super.initState();
        getName().then((){
           setState(() {
               name= "Welcome back, "+info.firstName;
           });
        });  
}


来源:https://stackoverflow.com/questions/64778981/retrieving-data-from-firestore-in-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!