Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I get data in the variable from sharedprefs and firestore database It won't displayed on screen

I am working on aflutter project where I have a screen called profile in that screen I want to display email, name of a user. Email I am getting from sharedPreference and send that email to firebase to get name from firestore database the problem is when user logged in to the app the name and email is empty no content is displayed on screen I don’t know why?

Here is the code:

class _ProfileState extends State<Profile> {
  String name = '';
  String email = '';
  String nameFromDatabase = '';
  String emailFromPrefs = '';
  FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  Future<void> getData() async {
    emailFromPrefs = (await sharedPreference().getCred('email'))!;
    nameFromDatabase = (await UserModel().getUser(email))!;
  }

  @override
  void initState() {
    super.initState();
    getData();
    setState(() {
      name = nameFromDatabase;
      email = emailFromPrefs;
    });
    print('Email is $email\nName is $name');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text('User Email is: $email',),
          Text('User Name is: $name'),
          //Logout Button
          MaterialButton(
              child: const Text('Logout'),
              onPressed: () {
                sharedPreference().reset();
                firebaseAuth
                    .signOut()
                    .then((value) => Navigator.pushAndRemoveUntil(
                        context,
                        PageRouteBuilder(
                          transitionDuration: const Duration(seconds: 1),
                          transitionsBuilder:
                              (context, animation, animationTime, child) {
                            animation = CurvedAnimation(
                                parent: animation,
                                curve: Curves.fastLinearToSlowEaseIn);
                            return ScaleTransition(
                              scale: animation,
                              alignment: Alignment.center,
                              child: child,
                            );
                          },
                          pageBuilder: (context, animation, animationTime) {
                            return LoginOrSignUp();
                          },
                        ),
                        (route) => false));
              },)
        ],
      ),
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because getData is future and you need to await for its result, the best approach is use FutureBuilder not call getData in initState. but a work around for it is call setState after data is ready. try this:

Future<void> getData() async {
    emailFromPrefs = (await sharedPreference().getCred('email'))!;
    nameFromDatabase = (await UserModel().getUser(email))!;
    setState(() {
       name = nameFromDatabase;
       email = emailFromPrefs;
    });
  }

and change your initState to this:

@override
  void initState() {
    super.initState();
    getData();
    
    print('Email is $email\nName is $name');
  }

FutureBuilder Approach:

return Scaffold(
  body: FutureBuilder<Map<String, dynamic>>(
         future: getData(),
         builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                Map<String, dynamic> data = snapshot.data ?? {};
                name = data["name"];
                email = data["email"];
                return Column(
                  children: [
                    Text(
                      'User Email is: $email',
                    ),
                    Text('User Name is: $name'),
                    //Logout Button
                    MaterialButton(
                      child: const Text('Logout'),
                      onPressed: () {
                        sharedPreference().reset();
                        firebaseAuth
                            .signOut()
                            .then((value) => Navigator.pushAndRemoveUntil(
                                context,
                                PageRouteBuilder(
                                  transitionDuration:
                                      const Duration(seconds: 1),
                                  transitionsBuilder: (context, animation,
                                      animationTime, child) {
                                    animation = CurvedAnimation(
                                        parent: animation,
                                        curve:
                                            Curves.fastLinearToSlowEaseIn);
                                    return ScaleTransition(
                                      scale: animation,
                                      alignment: Alignment.center,
                                      child: child,
                                    );
                                  },
                                  pageBuilder:
                                      (context, animation, animationTime) {
                                    return LoginOrSignUp();
                                  },
                                ),
                                (route) => false));
                      },
                    )
                  ],
                );
              }
          }
        },
      ),
  );

also change your getData to this:

Future<Map<String, dynamic>> getData() async {
    emailFromPrefs = (await sharedPreference().getCred('email'))!;
    nameFromDatabase = (await UserModel().getUser(email))!;

    return {"email":emailFromPrefs,"name":nameFromDatabase};
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading