栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Flutter:如何保持用户登录和注销

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Flutter:如何保持用户登录和注销

您可以从api获取响应代码200后,在“共享首选项”中输入一个条目。

 SharedPreferences prefs = await SharedPreferences.getInstance(); prefs?.setBool("isLoggedIn", true);

然后您可以在通过共享首选项检查状态后浏览用户

Future<void> main() async {  SharedPreferences prefs = await SharedPreferences.getInstance();  var status = prefs.getBool('isLoggedIn') ?? false;  print(status);  runApp(MaterialApp(home: status == true ? Login() : Home()));}

更新:-

另一种方法是,您也可以将逻辑添加到初始屏幕,初始屏幕应该是应用程序的入口点

class SplashScreen extends StatefulWidget {  @override  State<StatefulWidget> createState() {    // TODO: implement createState    return _SplashScreenState();  }}class _SplashScreenState extends State<SplashScreen> {  @override  void initState() {    // TODO: implement initState    super.initState();    startTimer();  }  @override  Widget build(BuildContext context) {    return Scaffold(      body: Container(        decoration: BoxDecoration(          image: DecorationImage(   image: AssetImage("assets/images/clinician_splash.png"),   fit: BoxFit.cover),        ),      ),    );  }  void startTimer() {    Timer(Duration(seconds: 3), () {      navigateUser(); //It will redirect  after 3 seconds    });  }  void navigateUser() async{    SharedPreferences prefs = await SharedPreferences.getInstance();    var status = prefs.getBool('isLoggedIn') ?? false;    print(status);    if (status) {      Navigation.pushReplacement(context, "/Home");    } else {      Navigation.pushReplacement(context, "/Login");    }  }}

对于注销,请在注销按钮的onPress事件中添加以下功能:

void logoutUser(){SharedPreferences prefs = await SharedPreferences.getInstance();prefs?.clear()  Navigator.pushAndRemoveUntil(      context,       ModalRoute.withName("/SplashScreen"),      ModalRoute.withName("/Home")    );}

为了安全:-

在示例中,我使用了不安全的SharedPreferences。为安全起见,您可以将SharedPreferences更改为flutter_secure_storage。

https://pub.dev/packages/flutter_secure_storage#-readme-
tab-



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号