我已经实现了登录和注销按钮,但是不知道如何显示/隐藏按钮(Listview中的列表)。按钮位于Listview(位于抽屉内)中,想要在顶部登录时显示按钮,如果用户已登录,则希望在Listview的末尾显示注销
用于验证登录名是否以共享首选项存储的用户ID
SharedPreferences prefs = await SharedPreferences.getInstance();
dynamic userid = prefs.getInt('userId');
Padding(
padding: EdgeInsets.only(top: 10, bottom: 10),
child: InkWell(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=> LoginandSignupScreen()));
},
child: Row(
children: <Widget>[
Expanded(flex: 2, child: Icon(Icons.card_travel)),
Expanded(
flex: 10,
child: Text(
'Login',
style: TextStyle(fontSize: 15),
))
],
),
),
),
Padding(
padding: EdgeInsets.only(top: 10, bottom: 10),
child: InkWell(
onTap: (){
Provider.of<Auth>(context, listen: false).logout();
Navigator.push(context, MaterialPageRoute(builder: (context)=> HomeScreen()));},
child: Row(
children: <Widget>[
Expanded(flex: 2, child: Icon(Icons.card_travel)),
Expanded(
flex: 10,
child: Text(
'Logout',
style: TextStyle(fontSize: 15),
))
],
),
),
),
答案 0 :(得分:0)
您必须维护bool才能知道用户是否已登录。您可以使用三元运算符来验证这一点,类似于您可以申请登录的
userid != null ? Padding(
padding: EdgeInsets.only(top: 10, bottom: 10),
child: InkWell(
onTap: (){
Provider.of<Auth>(context, listen: false).logout();
Navigator.push(context, MaterialPageRoute(builder: (context)=> HomeScreen()));},
child: Row(
children: <Widget>[
Expanded(flex: 2, child: Icon(Icons.card_travel)),
Expanded(
flex: 10,
child: Text(
'Logout',
style: TextStyle(fontSize: 15),
))
],
),
),
) : Container();
答案 1 :(得分:0)
请参阅车丹,我有一种非常简单的方法向您展示如何实现这一目标。
- 假设
userid
不存在,那么它将null
返回到您的userid
变量
现在,在Flutter
中,您可以执行check
,并在此基础上显示/隐藏某些内容。
var somthing = data
if(something != null) // show your Widget
else Container() // this is usually done to show the empty widget, which is as good as hiding the data and showing up a non-space taking widget
在当前情况下,您可以根据上述方法显示/隐藏按钮。我们使用一个称为ternary operator
的条件运算符。您可以详细了解here。
// If user is not logged in, then Login will not show up, that means userid should be null
userid == null ?
Padding(
padding: EdgeInsets.only(top: 10, bottom: 10),
child: InkWell(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=> LoginandSignupScreen()));
},
child: Row(
children: <Widget>[
Expanded(flex: 2, child: Icon(Icons.card_travel)),
Expanded(
flex: 10,
child: Text('Login', style: TextStyle(fontSize: 15)))
]
)
)
) : Container(), // if the userid is not null then Container() will be shown,
// If user is logged in, then Logout will not show up, that means userid should not be null
userid != null ?
Padding(
padding: EdgeInsets.only(top: 10, bottom: 10),
child: InkWell(
onTap: (){
Provider.of<Auth>(context, listen: false).logout();
Navigator.push(context, MaterialPageRoute(builder: (context)=> HomeScreen()));},
child: Row(
children: <Widget>[
Expanded(flex: 2, child: Icon(Icons.card_travel)),
Expanded(
flex: 10,
child: Text('Logout',style: TextStyle(fontSize: 15)))
]
)
)
) : Container() // if the userid is null then Container() will be shown
这就是您的处理方式。希望对您有所帮助。让我知道您是否需要任何澄清。到那时,学习愉快:)