[英]How to use shared preferences to have a one-time login in flutter?
我搜索了 google/stackoverflow 並嘗試了很多但沒有任何效果。 這是我想要的流程:
到目前為止 1 和 2 有效。 但是當用戶終止/關閉應用程序並再次重新啟動它時,他們不會被定向到主頁,而是再次被定向到登錄頁面。
啟動畫面的代碼:
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
startTimer();}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 150,
width: 150,
child: new SvgPicture.asset(
'assets/logo.png'
),
),
),
);
}
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');
print(status);
if (status == true) {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => HomePage());
} else {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => LoginScreen()));
}
}}
注銷按鈕的代碼:
void logoutUser() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs?.clear();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (BuildContext context) => SplashScreen()),
ModalRoute.withName("/login"),
);
}
對於冗長的帖子感到抱歉,如果有人能指出我哪里出錯了,我將非常感謝您的幫助。 或者flutter有沒有其他方法可以實現一次性登錄,謝謝!
我知道我的回答現在晚了。 但是,如果您使用的是 FirebaseAuth,這將自動緩存您的登錄、注銷日志。 所以你不需要將它存儲到 pref。 只需在啟動屏幕時執行額外的步驟以檢查用戶的最后狀態是登錄還是通過以下方式注銷。 並且此信息可用於重定向到所需的屏幕。
代碼:
Future<bool> checkIfAlreadySignedIn () async {
late bool _isAlreadySignedIn;
await FirebaseAuth.instance
.authStateChanges()
.listen((event) async {
if (event == null) {
print('Currentyl signed out');
_isAlreadySignedIn = false;
} else {
_isAlreadySignedIn = true;
}
});
return _isAlreadySignedIn;
}
您在哪里將“isLoggedIn”首選項設置為 true?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.