您可以从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-



