提问者:小点点

颤振-使用重定向到新屏幕。然后(),提供程序。of()和Navigator


我有一个按钮,在初次点击/点击/触摸时,它会发布到API,并根据身份验证返回true或false。

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;
  }

成功验证后,它不会按预期重定向到新屏幕。我错过了什么还是我的逻辑有缺陷?


共1个答案

匿名用户

wait旨在中断流程,直到async方法完成。然后然而不会中断流程(意味着将执行下一条指令),但使您能够在异步方法完成时运行代码。

在代码中:

问题与您的login方法有关。您使用了带有wait,然后,您不需要同时使用两者。

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'
      });
      var decodedResponse = jsonDecode(response.body);
      if(decodedResponse['token'] != ''){
        return true;
      }
    }
    catch(e){
      errorMsg = e.toString();
      notifyListeners();
      return false;
    }
    return false;
  }

您可以在SO问题中找到更多示例:

  • 异步/等待/然后飞镖/颤振