簡體   English   中英

Flutter - 使用.then()、Provider.of() 和 Navigator 重定向到新屏幕

[英]Flutter - redirect to new screen using .then(), Provider.of(), and Navigator

我有一個按鈕,在初始點擊/點擊/觸摸時,它 POST 到 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; }

身份驗證成功后,它不會按預期重定向到新屏幕。 我錯過了什么或者我的邏輯有缺陷嗎?

await旨在中斷流程,直到async方法完成。 然而, then不會中斷流程(意味着將執行下一條指令),但使您能夠在異步方法完成時運行代碼。

在你的代碼中:

問題是關於您的login方法。 您將awaitthen一起使用,您不需要同時使用兩者。

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 問題中找到更多示例:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM