首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >让用户登录应用程序的可能方法是什么?

让用户登录应用程序的可能方法是什么?
EN

Stack Overflow用户
提问于 2021-12-30 17:51:49
回答 2查看 418关注 0票数 0

我正在开发一个颤振项目,该项目由一个登录屏幕和主屏幕以及其他一些附加屏幕组成。我在登录屏幕中使用firebase authentication进行身份验证。

现在,当我登录到应用程序时,它会根据需要将我路由到主页。但是,在我关闭应用程序并重新打开应用程序之后,我将不得不再次登录到应用程序。如何在用户第一次登录应用程序后永久保持用户登录。(换句话说,我希望在用户登录应用程序之后,保持用户登录,并将用户保存在主页中,即使用户关闭并重新打开应用程序)。

为了进一步参考,我将附上我的login.dartauth_services.dartwrapper.dart文件。

Login.dart

代码语言:javascript
复制
class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    TextEditingController emailController;
    TextEditingController passwordController;
    final authService = Provider.of<AuthService>(context);
    emailController = TextEditingController();
    passwordController = TextEditingController();
    return Scaffold(
        backgroundColor: Colors.white,
        body: SingleChildScrollView(
          child: Form(
              key: _formKey,
              child: Column(children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 60.0),
                  child: Center(
                    child: Container(
                        width: 300,
                        height: 380,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50.0)),
                        child: Image.asset(
                          'assets/images/logo.png',
                        )),
                  ),
                ),
                const SizedBox(height: 15.0),
                Padding(
                  padding: EdgeInsets.only(
                      left: 25.0, right: 25.0, top: 0, bottom: 0),
                  child: TextFormField(
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter the email.';
                      }
                      return null;
                    },
                    controller: emailController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(60),
                        ),
                        prefixIcon: const Icon(Icons.mail),
                        labelText: 'E-Mail',
                        hintText: 'admin@gmail.com'),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(
                      left: 25.0, right: 25.0, top: 15, bottom: 0),
                  child: TextFormField(
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter the password.';
                      }
                      return null;
                    },
                    controller: passwordController,
                    obscureText: true,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(60),
                        ),
                        prefixIcon: const Icon(Icons.vpn_key),
                        labelText: 'Password',
                        hintText: 'Enter your Password'),
                  ),
                ),
                const SizedBox(
                  height: 100,
                ),
                TextButton(
                    onPressed: () {
                      if (_formKey.currentState == null) {}
                      if (_formKey.currentState!.validate()) {
                        authService.signInWithEmailAndPassword(
                            context,
                            emailController.text.trim(),
                            passwordController.text.trim());
                      }
                      // authService.signInWithEmailAndPassword(
                      //     context,
                      //     emailController.text.trim(),
                      //     passwordController.text.trim());
                    },
                    child: const Text(
                      'Login',
                      textAlign: TextAlign.center,
                    )),
                MaterialButton(
                    onPressed: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => forgotPassword()));
                    },
                    child: Text(
                      'Forgot Password',
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 13.0, color: Colors.red.shade900),
                    ))
              ])),
        ));
  }
}

auth_services.dart

代码语言:javascript
复制
class AuthService {
  //Creating an instance of firebase.
  final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;

  User? _userFromFirebase(auth.User? user) {
    if (user == null) {
      return null;
    }
    return User(user.uid, user.email);
  }

  Stream<User?>? get user {
    return _firebaseAuth.authStateChanges().map(_userFromFirebase);
  }

  Future<User?> signInWithEmailAndPassword(
    BuildContext context,
    String email,
    String password,
  ) async {
    try {
      final credential = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      return _userFromFirebase(credential.user);

      throw Exception('Some Error occured. ');
    } on auth.FirebaseAuthException catch (e, _) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(e.toString()),
      ));
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(e.toString()),
      ));
    }
  }

  Future<void> signOut() async {
    return await _firebaseAuth.signOut();
  }
}

wrapper.dart

代码语言:javascript
复制
class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    return StreamBuilder<User?>(
        stream: authService.user,
        builder: (_, AsyncSnapshot<User?> snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            final User? user = snapshot.data;
            return user == null ? Login() : dashboard();
          } else {
            return const Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }
        });
  }
}

提前谢谢大家。

EN

Stack Overflow用户

发布于 2021-12-30 17:56:00

Firebase已经将用户凭据保存在大多数平台上,而恢复则是应用程序重新启动/重新加载页面的时候。但是这需要对服务器进行调用,异步操作也是如此,所以一定要侦听authStateChanges (如图所示的这里 ),以便在用户恢复后得到通知。

如果您没有遇到这种情况,请编辑您的问题以显示再现此问题的最小代码

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70535074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档