簡體   English   中英

從 flutter 中的 API 獲得多重響應

[英]Get multiple response from API in flutter

我有一個用戶注冊 API 寫入節點,但 API 給了我三種類型的響應

  1. 如果注冊成功,那么下面的 JSON 就是響應
     {
      "message": "success",
      "ccontent": {
        "_id": "5ef7c4c414529241205fb590",
        "email": "sam@gmail.com",
        "password": "$2b$05$4TFPKJ83O7jSPhjtIIDj1ud5pjhS9GY.I0C.IFlBDyUFsd6i4E3Ci",
        "__v": 0
      }
    }
  1. 如果用戶已經存在,它只會給我一個字符串響應

    已經存在

  2. 如果發生錯誤

    發生了錯誤

我有一個未來的 function 來獲得 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);
  }
}

這僅在用戶注冊成功但失敗時發生錯誤,告訴未處理的異常“已經存在”或“發生錯誤”時才有效

在未來的 function 中,如何從 API 獲得所有類型的響應?

提前致謝。

如果響應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時,您還需要處理異常,以便您可以做出正確反應。

暫無
暫無

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

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