Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

Some Problems In Flutter Firebase Login

I tried coding a login and registration form in an app with firebase auth. There are some problems in my login from.

Please look at this loginForm function which will execute when login button is pressed.

Future loginForm() async {
    FormState formSate = _formKey.currentState;
    if (formSate.validate()) {
      final User firebaseUser = (await firebaseAuth
              .signInWithEmailAndPassword(
                  email: _emailcontroller.text,
                  password: _passwordcontroller.text)
              .catchError((errMsg) {
        displayToast("Error: " + errMsg.toString(), context);
      }))
          .user;

      if (firebaseUser != null) {
        setState(() {
          loading = true;
        });
        usersRef.child(firebaseUser.uid).once().then((DataSnapshot snap) async {
          if (snap.value != null) {
            SharedPreferences preferences =
                await SharedPreferences.getInstance();
            preferences.setString("email", _emailcontroller.text);
            Navigator.pushReplacement(context,
                MaterialPageRoute(builder: (context) {
              return LocationHome();
            }));

            displayToast("Succesfully LoggedIn!", context);
          } else {
            firebaseAuth.signOut();
            displayToast("No user found! Please try SignUp", context);
          }
        });
      } else {
        displayToast("Error Occured! Cannot log you in", context);
      }
    }
  }
}

You can see here that after login I have programmed it to navigate to Location Page.

But to make user stay logged in I have used a StreamBuilder and checking if snapshot.hasdata in the main file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MaterialApp(
    title: 'TaakStore',
    home: StreamBuilder(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
      if (snapshot.hasData) {
        print(snapshot);
        return Home();
      } else {
        return Login();
      }
    },
  ),
  ));
}

In this, you can see that if snapshot.hasdata it should navigate to home screen and if not data then nav to the login screen. The first time when a user opens the app the snapshot has no data so it will open a login screen which is perfect. But the problem is when the user clicks on login button instead of going to location screen it is directly going to home screen because the snapshot has data which is ridiculous.

If someone understand my problem please help me

question from:https://stackoverflow.com/questions/65713740/some-problems-in-flutter-firebase-login

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the problem is occuring by using the streamBuilder as streamBuilder continously keeps looking for stream or data and as soon it found the appropriate data it performs the assigned function which is navigating the user to the homeScreen() instead of LocationScreen()

Repleace StreamBuilder on the Main() with the bellow code:

   if (FirebaseAuth.instance.currentUser != null) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => Home(),
        ),
      );
    } else {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => Location(
         
          ),
        ),
      );
    }

This will not keep on looking for the stream and only execute the function once when the app is restarted. The same method have been suggested by FirebaseFlutter .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...