让用户保持登录状态

Posted

技术标签:

【中文标题】让用户保持登录状态【英文标题】:Keep the user logged in flutter 【发布时间】:2020-11-23 11:05:03 【问题描述】:

我正在做一个应用程序,我正在处理身份验证部分。我想知道在我重新加载应用程序后如何让我的用户保持登录状态。这是我用于记录的代码,我已经使用了共享首选项,但仍然无法正常工作。我应该在代码中添加什么或更改?我也应该在 Homepage() 中添加一些内容吗? 我忘了提到当我打开应用程序时我的第一页是 main.dart,第二个是 LoginScreen(您可以在其中选择您登录的帐户类型:facebook、google、电子邮件)

import 'package:flutter/material.dart';
import 'SignUp.dart';
import 'brazierContainer.dart';
import 'package:google_fonts/google_fonts.dart';
import 'LoginScreen.dart';
import 'HomePage.dart';
import 'auth.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async 
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var email = prefs.getString('email');
  print(email);
  runApp(MaterialApp(home: email == null ? LoginPage() : Homepage()));


class LoginPage extends StatefulWidget 
  LoginPage(Key key, this.title) : super(key: key);

  final String title;

  @override
  _LoginPageState createState() => _LoginPageState();


class _LoginPageState extends State<LoginPage> 
  final _formKey = GlobalKey<FormState>();
  String email = '';
  String password = '';
  String error = '';
  bool loading = false;
  final Authentication authentication = Authentication();
  @override
  Widget build(BuildContext context) 
    return loading
        ? Homepage()
        : Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            body: Container(
              height: 900.0,
              width: 500.0,
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 50.0),
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          icon: Icon(Icons.arrow_back_ios, color: Colors.blue),
                          onPressed: () 
                            Navigator.pushReplacement(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => LoginScreen()));
                          ,
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 40.0),
                    child: RichText(
                      text: TextSpan(
                        text: 'Tariffo',
                        style: TextStyle(
                            color: Colors.blue,
                            fontFamily: 'SignPainter',
                            fontSize: 60),
                      ),
                    ),
                  ),
                  SizedBox(
                      height: 400.0,
                      child: Form(
                        key: _formKey,
                        child: Column(
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: 40.0, right: 40.0, top: 40.0),
                              child: TextFormField(
                                validator: (val) =>
                                    val.isEmpty ? 'enter email' : null,
                                onChanged: (val) 
                                  setState(() => email = val);
                                ,
                                style: TextStyle(color: Colors.black),
                                decoration: InputDecoration(
                                    hintText: 'enter email',
                                    hintStyle: TextStyle(
                                        fontFamily: 'Antra',
                                        fontSize: 12.0,
                                        color: Colors.black)),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: 40.0, right: 40.0, top: 40.0),
                              child: TextFormField(
                                validator: (val) => val.length < 8
                                    ? 'enter password > 8 digits'
                                    : null,
                                onChanged: (val) 
                                  setState(() => password = val);
                                ,
                                style: TextStyle(color: Colors.black),
                                decoration: InputDecoration(
                                    hintText: 'enter password',
                                    hintStyle: TextStyle(
                                        fontFamily: 'Antra',
                                        fontSize: 12.0,
                                        color: Colors.black)),
                                obscureText: true,
                              ),
                            ),
                            SizedBox(height: 50),
                            Padding(
                              padding: const EdgeInsets.only(top: 40.0),
                              child: MaterialButton(
                                height: 50,
                                minWidth: 300,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10)),
                                color: Colors.blue,
                                onPressed: () async 
                                  SharedPreferences prefs =
                                      await SharedPreferences.getInstance();
                                  prefs.setString(
                                      'email', 'useremail@gmail.com');
                                  if (_formKey.currentState.validate()) 
                                    setState(() => loading = true);
                                    dynamic result = await authentication
                                        .signUpWithEmailAndPassword(
                                            email, password);
                                    if (result == null) 
                                      setState(() => error =
                                          'Sorry,These credentials will not work out');
                                      loading = false;
                                    
                                  
                                ,
                                child: Text(
                                  'Sign in',
                                  style: TextStyle(
                                      fontFamily: 'Antra', color: Colors.white),
                                ),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 10, horizontal: 10),
                              alignment: Alignment.centerRight,
                              child: Text('Forgot Password ?',
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500)),
                            ),
                          ],
                        ),
                      )),
                  _createAccountLabel(),
                ],
              ),
            ),
          );
  

  Widget _createAccountLabel() 
    return InkWell(
      onTap: () 
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => SignupPage()));
      ,
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 20),
        padding: EdgeInsets.all(15),
        alignment: Alignment.bottomCenter,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Don't you have an account ?",
              style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              'Register',
              style: TextStyle(
                  color: Colors.blue,
                  fontSize: 13,
                  fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  

还有我的 main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'LoginScreen.dart';

void main() => runApp(new MaterialApp(
      home: new MyApp(),
    ));

class MyApp extends StatefulWidget 
  @override
  _MyAppState createState() => new _MyAppState();


class _MyAppState extends State<MyApp> 
  @override
  void initState() 
    super.initState();
    new Future.delayed(
        const Duration(seconds: 3),
        () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginScreen()),
            ));
  

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          backgroundColor: Colors.blue,
          body: Center(
            child: Text(
              "Tariffo",
              style: TextStyle(
                  color: Colors.white, fontFamily: 'SignPainter', fontSize: 60),
            ),
          )),
    );
  

【问题讨论】:

【参考方案1】:

您必须显示 main.dart 文件 您是否从 main.dart 中的 SharedPreferences 下载信息?如果是这样,您需要在进入登录页面之前检查您是否已经从 SharedPreferences 下载了一些数据,并且不要打开登录页面。

【讨论】:

在主要飞镖我只有应用程序的标志 并重定向到登录页面,对吗?显示这个文件,我会写下如何让它工作 Main.dart -> LoginScreen.dart -> SignUp.dart -> LoginPage.dart -> Homepage.dart @svraluca1 好的,您必须在 main.dart 文件中检查 sharedPreferences 是否为空 - 如果不为空,请不要重定向到 loginPage String _email; SharedPreferences sharedPrefs; sharedPrefs = await SharedPreferences.getInstance(); email = sharedPrefs.getString('email') ?? ''; if ('' == email) Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; LoginScreen()), ) @svraluca1 当然,您将电子邮件更改为 _email - 我的错。并在你使用路由的地方使用这个if... - initState 代替new Future.delayed( const Duration(seconds: 3), () =&gt; Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; LoginScreen()), ));

以上是关于让用户保持登录状态的主要内容,如果未能解决你的问题,请参考以下文章

Firebase:如何让 Android 用户保持登录状态?

我是 Flutter Web 的新手,如何使用 Firebase 电话身份验证对用户进行身份验证,有没有办法让用户保持登录状态?

App保持登录状态的常用方法

刷新后如何让用户保持登录到 Firebase 应用程序?

在 React.JS 中刷新后,如何让用户保持登录到 firebase?

DRF框架之用户登录状态保持