简体   繁体   中英

How to display a circular progress indicator whilst waiting for Authentication from Firebase

I have a sign-in page that is authenticated by Firebase, and I want to display a circular progress indicator whilst is still authenticating. I inserted if statements in the catch block of the sign-in button that handles the errors that may occur within the signing in process

I want to display the circular indicator if there's is no error that is thrown by the firebase Server I am new to coding, please help me.

Below is a code of the sign-in page

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:user_details/fromJP/Scan_QR.dart';
import 'package:user_details/fromJP/load_widget.dart';
import 'Register.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final formKey = GlobalKey<FormState>();
  bool loading = false;

  TextEditingController _emailController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  String errorMessage;

  @override
  Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> _scafoldKey = GlobalKey<ScaffoldState>();
    return loading
        ? Loading()
        : Scaffold(
            key: _scafoldKey,
            appBar: AppBar(
              title: Text("Jinjer Pay"),
            ),
            body: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage("lib/bg.jpg"), fit: BoxFit.cover)),
              child: Form(
                key: formKey,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                          margin: EdgeInsets.fromLTRB(15, 0, 15, 0),
                          padding: EdgeInsets.all(35),
                          decoration: BoxDecoration(
                              shape: BoxShape.rectangle,
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          child: Column(
                            children: <Widget>[
                              SizedBox(
                                height: 20,
                              ),
                              TextFormField(
                                decoration:
                                    new InputDecoration(hintText: "Email"),
                                keyboardType: TextInputType.emailAddress,
                                controller: _emailController,
                              ),
                              SizedBox(
                                height: 20,
                              ),
                              TextFormField(
                                decoration:
                                    new InputDecoration(hintText: "Password"),
                                obscureText: true,
                                enableSuggestions: false,
                                controller: _passwordController,
                              ),
                              SizedBox(
                                height: 20,
                              ),
                              RaisedButton(
                                child: Text(
                                  "Log In",
                                  style: TextStyle(fontSize: 19),
                                ),
                                color: Colors.amberAccent,
                                elevation: 10,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(15)),
                                onPressed: () async {
                                  if (formKey.currentState.validate()) {
                                    setState(() => loading = true);

                                    try {
                                      UserCredential res;
                                      String userID;

                                      res = (await FirebaseAuth.instance
                                          .signInWithEmailAndPassword(
                                              email: _emailController.text,
                                              password:
                                                  _passwordController.text));
                                      userID = res.user.uid;

                                      if (res == null) {
                                        setState(() {
                                          loading = false;
                                        });
                                      }
                                      if (res != null) {
                                        Navigator.pop(context);
                                        Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) => Scan_QR()),
                                        );
                                      }
                                    } catch (e) {
                                      if (e.code == "unknown") {
                                        Fluttertoast.showToast(
                                            msg:
                                                "Email/Password Field cannot be Empty",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      if (e.code == "wrong-password") {
                                        Fluttertoast.showToast(
                                            msg: "Your password is incorrect",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      if (e.code == "invalid-email") {
                                        Fluttertoast.showToast(
                                            msg:
                                                "Email/Password Field cannot be Empty",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      if (e.code == "user-not-found") {
                                        Fluttertoast.showToast(
                                            msg:
                                                "No User found with this email",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      if (e.code == "user-disabled") {
                                        Fluttertoast.showToast(
                                            msg:
                                                "user with this email has been disabled",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      if (e.code == "too-many-requests") {
                                        Fluttertoast.showToast(
                                            msg:
                                                "Too many requests, try again later",
                                            toastLength: Toast.LENGTH_SHORT,
                                            gravity: ToastGravity.CENTER,
                                            timeInSecForIosWeb: 1,
                                            backgroundColor: Colors.redAccent,
                                            textColor: Colors.white,
                                            fontSize: 16.0);
                                      }
                                      print(e);
                                      //_emailController.text = "";
                                      _passwordController.text = "";
                                    }
                                  }
                                },
                              ),
                              SizedBox(
                                height: 20,
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    "Not Registered? ",
                                    style: TextStyle(fontSize: 19),
                                  ),
                                  SizedBox(width: 5),
                                  InkWell(
                                    onTap: () {
                                      Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) => Register()),
                                      );
                                    },
                                    child: Text(
                                      "Register",
                                      style: TextStyle(
                                          color: Colors.blue, fontSize: 19),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 20,
                                  ),
                                ],
                              ),
                            ],
                          ))
                    ],
                  ),
                ),
              ),
            ),
          );
  }
}

You can showDialog with Center(child:CircularProgressIndicator()) in try block and Navigator.pop(context); when you succeeded or get thrown error

You can create a bool isLoading property in your widget that initializes to false. then in your function call you can set the state and change your isLoading to true before making the call to firebase. when the call to firebase completes either successfully or throws an error you can then set the state and change isLoading to false again.

Finally, in the UI you can use conditionals to show a circular progress indicator if isLoading is true.

I added this block at the beginning of the catch block

if(FirebaseAuth.instance.currentUser.uid != e.code)
                                        {
                                          setState(() {
                                            loading = false;
                                          });
                                        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM