我正在開發一個 flutter 專案,該專案由登錄螢屏和主螢屏以及其他一些附加螢屏組成。我firebase authentication在登錄螢屏中用于身份驗證。
現在,當我登錄到應用程式時,它會根據需要將我路由到主頁。但是在我關閉應用程式并重新打開應用程式后,我將不得不再次登錄該應用程式。在用戶第一次登錄應用程式后,如何永久保持用戶登錄狀態。(換句話說,即使用戶關閉并重新打開應用程式,我也希望在用戶登錄應用程式后保持用戶登錄狀態并將用戶保留在主頁中)。
為了進一步參考,我將附上我的login.dart, auth_services.dart,wrapper.dart檔案。
Login.dart :
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: '[email protected]'),
),
),
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 :
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 :
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(),
),
);
}
});
}
}
Thank you all so much in advance.
uj5u.com熱心網友回復:
Firebase 已在大多數平臺上保留用戶憑據,并在應用重新啟動/頁面重新加載時恢復。但這需要呼叫服務器,因此是異步操作,因此請務必authStateChanges按照此處所示進行監聽,以便在用戶恢復后獲得通知。
如果您沒有遇到這種情況,請編輯您的問題以顯示重現此問題的最少代碼。
uj5u.com熱心網友回復:
為此,您可以創建一個變數Boolean ,例如isLoggedIn,當用戶登錄時,您可以為其分配 true 值,并且您必須locally使用本地存盤(如SharedPreference )保存它。
之后當 ofisLoggedIn為 true 或 not is true 意味著已經logged在 else 中not。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398569.html
標籤:firebase flutter dart firebase-authentication state
下一篇:在dartpub中更新已發布的包
