Flutter-使用.Then(),提供商。F()和Navigator重定向到新屏幕
我有一个按钮,在初始单击/点击/触摸时,它将其发布到API,然后根据AUTH返回True或False。
onpressed:()=> { 提供者。 。 if(value == true) navigator.pushreplacementamed(上下文,'/home') }), },,
Future< bool> login()async { 尝试{ var paryload = jsonencode({ “电子邮件”:usrname, “密码”:PSWD }); map< string,Dynamic>响应=等待fetch.post(url,正文:有效载荷,标头:{ “接受”:'application/json', 'content-type':'应用程序/json' })) 。 如果(响应['token']!=''){ 返回true; } } 捕获(e){ errormsg = e.tostring(); notifyListeners(); 返回false; } 返回false; }
在成功的身份验证中,它不会按预期重定向到新屏幕。我是否缺少某些东西,还是我的逻辑有缺陷?
I have a button which on initial click/tap/touch, it POST to API and return true or false based on auth.
onPressed: ()=>{ Provider.of<Login>(context, listen: false).login() .then((value) => { if(value == true) Navigator.pushReplacementNamed(context, '/home') }), },
Future<bool> login() async { try{ var payload = jsonEncode({ 'email': usrname, 'password': pswd }); Map<String,dynamic> response = await fetch.post(url, body:payload, headers: { 'Accept':'application/json', 'content-type': 'application/json' }) .then((value) => jsonDecode(value.body)); if(response['token'] != ''){ return true; } } catch(e){ errorMsg = e.toString(); notifyListeners(); return false; } return false; }
On successful authentication, it doesn't redirect to new screen as intended. Am I missing something or my logic is flawed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
await
旨在中断流程,直到async
方法完成。然而,then
不会中断流程(意味着将执行下一条指令),但使您能够在异步方法完成时运行代码。在您的代码中:
问题与您的
login
方法有关。您使用了await
和then
,不需要同时使用两者。您可以在 SO issues 中找到更多示例:
await
is meant to interrupt the process flow until theasync
method has finished.then
however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.In your code :
The issue is about your
login
method. You used anawait
with athen
, you don't need to use both at the same time.You can find more examples in SO issues :