【问题标题】:Get multiple response from API in flutter在颤动中从 API 获取多个响应
【发布时间】:2020-10-18 08:02:09
【问题描述】:

我有一个用 node 编写的用户注册 API,但该 API 给了我三种类型的响应

  1. 如果注册成功,那么下面的 JSON 就是响应
     {
      "message": "success",
      "ccontent": {
        "_id": "5ef7c4c414529241205fb590",
        "email": "sam@gmail.com",
        "password": "$2b$05$4TFPKJ83O7jSPhjtIIDj1ud5pjhS9GY.I0C.IFlBDyUFsd6i4E3Ci",
        "__v": 0
      }
    }
  1. 如果用户已经存在,它只会给我一个字符串响应

    已经存在

  2. 如果发生错误

    发生错误

我有一个未来函数可以从 API 获取响应

class RegistrationService {
  String registrationUrl = 'http://192.168.1.6:8080/api/user/create';

  Future userRegistration(email, password) async {
    Response response = await post(registrationUrl,
        body: {"email": email, "password": password});
    var result = jsonDecode(response.body);
    return RegistrationResponse.fromJson(result);
  }
}

这仅在用户注册成功但失败时发生错误,告诉未处理的异常'已经存在'或'错误发生'

如何在这个未来的函数中从 API 获得所有类型的响应?

提前致谢。

【问题讨论】:

    标签: android ios firebase flutter flutter-layout


    【解决方案1】:

    如果响应是already-existserror-occurred,您可以抛出异常

    class RegistrationService {
      String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
    
      Future<Map<String, dynamic> userRegistration(email, password) async {
        Response response = await post(registrationUrl,
            body: {"email": email, "password": password});
        
        if (userAlreadyExist(response.body)) {
           // already-exists response
            throws UserAlreadyExistException();
        }
        else if (errorOccurred(response.body)) {
            // error occurred response
            throws SomeOtherException();
        }
    
        var result = jsonDecode(response.body);
        return RegistrationResponse.fromJson(result);
      }
    }
    

    您需要实现方法userAlreadyExisterrorOccurred 来检测这种情况并确定每种情况下最好的异常类型。当您调用userRegistration 时,您还需要处理异常,以便做出正确反应。

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 2018-11-20
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多