【问题标题】:Building widget in Flutter when response statusCode on API call is >400当 API 调用的响应 statusCode 大于 400 时在 Flutter 中构建小部件
【发布时间】:2018-06-25 07:40:23
【问题描述】:

所以我试图在这里调用 REST API 进行登录。这是在我的 api_services.dart 中,我在其中调用应用程序的所有 API。

api_services.dart

Future<User> loginUser(String email, String password) 
async {
    final response = await http.post(serverOauthUrl+'/token',
    headers: {
    HttpHeaders.AUTHORIZATION: "xxxx"
  },
  body: {
     "email":"$email",
     "password":"$password",
  }
);
print(response.statusCode);
final responseJson = json.decode(response.body);
return new User.fromJson(responseJson);
}

有两种方法可以在我的 UI 文件中调用此 loginUser() 方法并获得响应。一个使用 then() 方法,另一个使用 FutureBuilder。但是,在任何一种方法中,我都可以获得状态码。我的用例是当状态码 >400 时,我将构建一个显示错误消息的小部件。

login_screen.dart

then() 方法代码:

_callLoginAPI(String email, String password){
  loginUser(userName, password, "password").then((response) {
        response.data.token;
       // want my status code here as well along with response data
    }
    else
    {
      //todo show something on error
    }
  }, onError: (error) {
    debugPrint(error.toString());
  });


}

或者使用 FutureBuilder :

return new FutureBuilder<User>(

      future: loginUser(email, password),
      builder: (context, snapshot) {

        if (snapshot.hasData) {
          print(snapshot.data.token);
        } else if (snapshot.hasError) {
          print(snapshot.error);
          return new Text("${snapshot.error}");
        }
        return new CircularProgressIndicator();
      },
    );

我想做的是这样的

if(response.statusCode > 400)
   return new Text("Error"):</code>

【问题讨论】:

    标签: rest dart flutter flutter-layout


    【解决方案1】:

    感谢@Thomas,这个问题得到了解决。实际上是一个简单的解决方案。

    添加代码中的更改以供其他初学者遵循:

    api_services.dart

    Future<http.Response> loginUser(String email, String password) async {
      final response = await http.post(serverOauthUrl+
        '/token',
        headers: {
        HttpHeaders.AUTHORIZATION: "Basic xxx"
        },
        body: {
          "email":"$email",
          "password":"$password",
        }
      );
    
      return response;
    }
    

    因此,我返回的是 http.Response 对象,而不是用户,现在我可以从 UI 文件中检索所有必需的信息。

    像这样:

    final responseJson = json.decode(response.body);
          User user = User.fromJson(responseJson);
          print(user.userName);
    

    希望对某人有所帮助

    【讨论】:

      【解决方案2】:

      你为什么不返回一个 Api Result 对象而不是一个包含错误代码和用户的用户? 然后,您可以根据状态代码在 FutureBuilder 上构建不同的小部件。

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2021-09-22
        • 1970-01-01
        • 2021-02-13
        • 2020-06-09
        • 2020-11-11
        • 2021-08-23
        • 2021-07-04
        • 1970-01-01
        相关资源
        最近更新 更多