从 API 获取响应并处理错误/在 flutter 中将 Bytestreem 转换为 Map

fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter

我正在尝试使用 API 与 PHP 后端通信,但我无法到达响应的 body。

我从邮递员那里得到了基本代码。 这是 body 响应的数据:

我需要到达消息,并在 UI 中显示错误,问题是 response.stream 它的类型是 Bytestreem,我无法将其转换为 Map

我的代码:

  Future<void> _authenticateUp(String email, String password,
      String passwordconfirmation, String username, String name,
      {String phonenumber}) async {

    var headers = {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    };

    var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));

    request.fields.addAll({
      'email': email,
      'password': password,
      'password_confirmation': passwordconfirmation,
      'username': username,
      'name': name,
      'phone_number': phonenumber
    });

    request.headers.addAll(headers);
    http.StreamedResponse response = await request.send();

    try {
      if (response.statusCode == 200) {
        await response.stream.bytesToString().then((value) {
          print(value);
        });
      } else {
        // here I want to print the message and the errors
      }
    } catch (e) {
      throw e;
    }
  }

添加这个 As for Error 你的 statusCode 不是 200

       try {
              if (response.statusCode == 200) {
                await response.stream.bytesToString().then((value) {
                  print(value);
                });
              } else {
        await response.stream.bytesToString().then((value) {
                  print(value);
    
    
    var jsonResponse = json.decode(response.body.toString());
    
    
               
        var nameError = jsonResponse["errors"]["name"][0];
        
        var emailError = jsonResponse["errors"]["email"][0];
        var usernameError = jsonResponse["errors"]["username"][0];
        var passwordError = jsonResponse["errors"]["password"][0];

//now can print any print(emailError);
                });
        }