Flutter如何在未经授权的情况下重定向到登录 [英] Flutter how to redirect to login if not authorized
问题描述
如果令牌在Flutter中已过期,我正尝试重定向到登录
I'm trying to redirect to login in case the token has been expired in Flutter
尝试获取帖子:
body: new Container(
padding: new EdgeInsets.only(bottom: 8.0),
color: Color(0xff2c3e4e),
child: FutureBuilder<List<Post>>(
future: api.getposts(),
builder: (context, snapshot) {
// doing stuff with response
}
)
)
获取帖子并捕获错误:
Future<List<Post>> getposts() async {
url = 'url';
var response = await http.get(url,
headers: {HttpHeaders.authorizationHeader: 'bearer ' + token},
);
//part I can't understand how to get to work, how do I push? This gives error about context not being defined.
if (response.body.toString().contains('Token is Expired')) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
LoginScreen()),
);
}
}
问题是,在这种情况下如何正确使用导航器,并且如果令牌已过期且需要更新,我可以重定向回loginScreen?就像在代码示例的注释中提到的那样,上下文使我未定义".
So the question is, how do I use the Navigator correctly in such cases and I can redirect back to loginScreen in case the token has been expired and needs to be renewed? Like mentioned in the comment in the code example, the context gives me "undefined".
这是否可能是我做事的方式,还是我只是简单地处理了整个支票?
Is this even possible the way I am doing it or am I simply handling the whole check completely wrong?
推荐答案
代码应具有单共振性.您的getPost
方法同时执行两项操作.您应该中断此函数,使其成功获取帖子或引发异常,并且其调用方将处理该异常.它的调用方btw必须在build
方法中,因为只有build
方法具有BuildContext context
,如下所示:
Code should have single resonpsibility. Your getPost
method are doing 2 things at the same time. You should break this function such that it either successfully get the the post, or throw exception, and its caller will handle the exception. Its caller btw must be within build
method, because only build
method has BuildContext context
, something like this:
if (response.body.toString().contains('Token is Expired')) {
throw new Exception("Token is Expired") // you may want to implement different exception class
}
body: new Container(
padding: new EdgeInsets.only(bottom: 8.0),
color: Color(0xff2c3e4e),
child: FutureBuilder<List<Post>>(
future: api.getposts(),
builder: (context, snapshot) {
if (snapshot.hasError) {
// you might want to handle different exception, such as token expires, no network, server down, etc.
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
return Container(); // return empty widget
}
if (snapshot.hasData) {
// do somthing with data
return Text('Some data here');
}
// has no data
return Text("Loading...");
}),
),
更新
感谢@TruongSinh,我知道了.
Thanks to @TruongSinh I got it figured out.
按照他的示例,找出有效的build导航器方法:
Followed his example and figured out the build navigator method which works:
if (snapshot.hasError) {
@override
void run() {
scheduleMicrotask(() {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
});
}
run();
}
这篇关于Flutter如何在未经授权的情况下重定向到登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!