我在做什么
有兩個頁面:個人資料和登錄頁面。
個人資料頁面首先顯示,但當用戶尚未登錄時,個人資料頁面不會顯示個人資料并顯示登錄按鈕。
組態檔代碼
bool loggedin = false; // If user already logged in return true
class Profile extends StatefulWidget {
const Profile({Key? key}) : super(key: key);
@override
_Profile createState() => _Profile();
}
class _Profile extends State<Profile> {
@override
Widget build(BuildContext context) {
return loggedin
? Column(children: [ //.... some user information
])
: needLogin(context);
}
}
Widget needLogin(BuildContext context) {
return Center(
TextButton(
onPressed: () {
Navigator.of(context).pushNamed("/login");
},
child: const Text(
"Login",
style: TextStyle(fontSize: 20),
)),
);
}
登錄頁面
// The code to login is omitted. if login succeeded do loggedin = true; in setState()
var user = FirebaseAuth.instance.currentUser;
if (user != null) {
Navigator.of(context).pop();
setState(() {
loggedin = true;
});
}
// Then back to profile page automatically
問題
我做了loggedin = true;,setState()但個人資料頁面仍然顯示needLogin().
我在needLogin()外面寫的原因StatefulWidget是為了與其他StatefulWidget.
題
呼叫setState()由Navigator.of(context).pushNamed().
uj5u.com熱心網友回復:
別
登錄
在小部件之外。
在以下范圍內使用它:
類 _Profile 擴展狀態 {
此外,您可能想研究一些狀態管理技術,例如 Provider with Change Notifier。它非常易于使用,并且可以完全滿足您的需求。
UI 不應包含業務邏輯,應基于某種控制器呈現。這使得代碼更加一致、可讀和可測驗。
uj5u.com熱心網友回復:
您必須編輯該needLogin方法并通過導航器將成功狀態/布林值傳回:
組態檔代碼
class Profile extends StatefulWidget {
const Profile({Key? key}) : super(key: key);
@override
_Profile createState() => _Profile();
}
class _Profile extends State<Profile> {
@override
Widget build(BuildContext context) {
return loggedin
? Column(children: [ //.... some user information
])
: needLogin(context, () => setState(() {loggedIn = true}));
}
}
Widget needLogin(BuildContext context, void Function() setStateFunction) {
return Center(
child: TextButton(
onPressed: () async {
await Navigator.of(context)
.pushNamed("/login")
.then((result) {
if (result as bool) {
setStateFunction.call();
}
});
},
child: const Text(
"Login",
style: TextStyle(fontSize: 20),
)),
);
}
登錄頁面
var user = FirebaseAuth.instance.currentUser;
if (user != null) {
Navigator.pop(context, true);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338154.html
上一篇:BoxPaintercreateBoxPainter([onChanged])=>引數onChanged不能為null
