Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

I have some problems in Flutter Firebase Login

I am coding an app for my company and I tried to add firebase authentication for login and registration to my app. The app shows no error and runs successfully.

But when a user tries to login with the wrong email and password, it is showing an internal flutter error instead of the toast I have programmed. And also I have used shared preferences to make users stay logged in.

So when a user tried to log in with the wrong credential it is showing an internal flutter error and when the app is re-opened, instead of going to the login screen, it is using the wrong credential and navigates user to Home Screen which is ridiculous.

These are the declared variables:

final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final _formKey = GlobalKey<FormState>();
TextEditingController _emailcontroller = TextEditingController();
TextEditingController _passwordcontroller = TextEditingController();
bool passvis = true;
bool loading = false;

And this is the function for login:

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) {
          if (snap.value != null) {
            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);
      }
    }
  }
}

And for Registration the code is below:

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

      if (firebaseUser != null) {
        Map userDataMap = {
          "name": _namecontroller.text.trim(),
          "email": _emailcontroller.text.trim(),
          "phone": _phonecontroller.text.trim(),
        };

        usersRef.child(firebaseUser.uid).set(userDataMap);

        displayToast("Succesfully Registered!", context);

        Navigator.pushReplacement(context,
            MaterialPageRoute(builder: (context) {
          return LocationHome();
        }));
      } else {
        displayToast("User was unable to create", context);
      }
    }
  }
}

The main.dart file is also coded correctly:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  SharedPreferences preferences = await SharedPreferences.getInstance();
  var circle = preferences.getString("circle");
  runApp(MaterialApp(
    title: 'TaakStore',
    home: circle == null ? Login() : Home(),
  ));
}

DatabaseReference usersRef =
    FirebaseDatabase.instance.reference().child("users");

Dont worry about the displayToast function. It is a function manually created with flutter toast.


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

1 Answer

0 votes
by (71.8m points)

To display a toast, try the following:

try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: _emailcontroller.text,
    password: _passwordcontroller.text
  );
} on FirebaseAuthException catch  (e) {
  displayToast("Error: " + e.message.toString(), context);
  print(e.message);
}

To check if the user is logged in or not use the following:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

authStateChanges() is of type Stream<User> which will listen for any changes on the state of a user. So if user is logged in, it will return a valid user object and you can navigate to the home screen. Therefore no need to use shared preferences.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...