12

In flutter, i use a php file which returns a json response from a db query, but when i try to decode json i getting this error:

E/flutter ( 8294): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled
Exception: FormatException: Unexpected character (at character 1)
E/flutter ( 8294): [{"0":"PRUEBA","usu_nombre":"PRUEBA"}]
E/flutter ( 8294): ^

Here is my dart function:

Future<String> iniciarSesion() async{
var usuario = textUsuario.text;
var password = textPassword.text;
var nombreUsuario;
var url ="http://192.168.1.37/usuario.php";

//Metodo post
var response = await http.post(
    url,
    headers:{ "Accept": "application/json" } ,
    body: { "usuario": '$usuario',"password": '$password'},
    encoding: Encoding.getByName("utf-8")
);
  List data = json.decode(response.body);
}

And code from my php file:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

include_once "Clases/conexion.php";

$usuario = $_POST['usuario'];
$password = $_POST['password'];

$consulta = "select usu_nombre
FROM usu_usuarios
WHERE usu_nusuario='$usuario'and usu_password='$password' and  usu_activo='SI'";

$mysql_obj = new Conectar();
$mysqli = $mysql_obj->crearConexion();

if($result = $mysqli->query($consulta)) {
if ($mysqli->affected_rows > 0) {
    while($row = $result->fetch_array()) {
        $myArray[] = $row;
    }
    header('Content-type: application/json');
    echo json_encode($myArray);
}else {
    header("HTTP/1.0 401 Datos Incorrectos");
    header('Content-type: application/json');
    $data = array("mensaje" => "Datos Incorrectos");
    echo json_encode($data);
}}
?>

I'm using HTTP dart dependence

Victor Ortiz
  • 791
  • 1
  • 12
  • 23

13 Answers13

29

Solve this issue with folowing code. For more refer here.

var pdfText= await json.decode(json.encode(response.databody);  
Kunchok Tashi
  • 2,413
  • 1
  • 22
  • 30
8

Finally i resolve the problem using laravel, returning the data in this way

return response()->json($yourData, 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'],
    JSON_UNESCAPED_UNICODE

I have noticed that this error occurs only in emulator, but not in a physical device.

Victor Ortiz
  • 791
  • 1
  • 12
  • 23
8

If you are using Dio and facing this kind of error then add :

 responseType: ResponseType.plain,

to your dio client. Complete dio client is as follows:

final Dio _dio = Dio(BaseOptions(
connectTimeout: 10000,
receiveTimeout: 10000,
baseUrl: ApiEndPoints.baseURL,
contentType: 'application/json',
responseType: ResponseType.plain,
headers: {
  HttpHeaders.authorizationHeader:'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQxNTU5MzYzLCJqdGkiOiJlOTBiZjIyYjI5YTg0YmRhYWNlZmIxZTY0Y2M2OTk1YyIsInVzZXJfaWQiOjF9.aDQzoYRawmXUCLxzEW8mb4e9OcR4L8YhcyjQIaBFUxk'
},

) )

Sahil Bansal
  • 609
  • 8
  • 6
3

Finally I resolve the problem in flutter, requesting the data in this way:

Map<String, String> headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    'Charset': 'utf-8'
};

http.get('localhost:8000/users', headers: headers)
fcdt
  • 2,371
  • 5
  • 14
  • 26
3

FormatException: Unexpected character (at character 1) Try again ^

The error is from flutter. It probably happened because you catch the http response using an object model, but your api response actually is a string or otherwise.

omega_mi
  • 243
  • 2
  • 11
1

I got this error on Android because I was using insecure http connections without setting application android:usesCleartextTraffic="true"/ in the AndroidManifest.

buckleyJohnson
  • 459
  • 4
  • 12
1

If you are requesting Multipart or Form-data then try to convert the response into simple http response using http.Response.fromStream(response)

Full code :

 String baseUrl ="https://yourUrl.com";
        var uri = Uri.parse(baseUrl);
        var request = new http.MultipartRequest("POST", uri);
        request.headers.addAll(headers);
        var multipartFile = await http.MultipartFile.fromPath(
            "file", videoFile.path);
        request.files.add(multipartFile);
        await request.send().then((response) {
        http.Response.fromStream(response).then((value) {
        print(value.statusCode);
        print(value.body);
        var cloudFlareResponse =
        CloudFlareApi.fromJson(json.decode(value.body));
        print(cloudFlareResponse.result.playback.hls);
        });
Aman
  • 71
  • 3
1

It may cause by Nginx image, file size limitation. Which will override your API response and your API returns the following error instead of your own defined error response structure:

I/flutter (25662): <html>

I/flutter (25662): <head><title>413 Request Entity Too Large</title></head>

I/flutter (25662): <body>

I/flutter (25662): <center><h1>413 Request Entity Too Large</h1></center>

I/flutter (25662): <hr><center>nginx/1.20.0</center>

I/flutter (25662): </body>

I/flutter (25662): </html>

If this is the issue, you can change allowed file, image size from your server Nginx settings to prevent this or check and resize image file before sending it thru your API.

You need to see what is the real error before trying to fix it. To make sure what is the real error, print the response before json decode and casting to map line like below:

debugPrint('Response body before decoding and casting to map: ');
      debugPrint(response.body.toString()); // this will print whatever the response body is before throwing exception or error


      Map responseMap = json.decode(response.body);
      debugPrint('responseMap is: ');
      debugPrint(responseMap.toString());
Elmar
  • 2,235
  • 24
  • 22
1

For me, it was due to the wrong URL. I mistakenly placed two / after my base URL.

TheFawad
  • 11
  • 2
0

I don't know why you are getting the  before your response, but I think it expects { as the first character, which is not true for your scenario. Have you added  yourself or do you know why it is a part of the response? If you can make it respond {"0":"PRUEBA","usu_nombre":"PRUEBA"} you should be home safe.

Why do you want to save your data as a List rather than a String? By having it as a String rather than a List you avoid the square brackets around your response.

flarkmarup
  • 5,129
  • 3
  • 24
  • 25
  • Thanks for your comment. I do not know where those symbols come from but I'm sure I do not add them to the response. – Victor Ortiz Apr 14 '19 at 17:12
0

That works for me, there was a problem with http ( http package ) and i replace it with httpClient from dart:io

Future login(String email, String password) async {

HttpClient httpClient = new HttpClient();
const url = "http://127.0.0.1/api/auth/login";
Map data = {
  "email": email,
  "password": password,
};
var body = json.encode(data);
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(data)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
print(reply);

}

Hamdi Abd
  • 1
  • 2
0

For me, changing the URL part from: "http://localhost:3001/mypage" to "http://127.0.0.1:3001/mypage" resolved it.

kahan x10
  • 215
  • 2
  • 12
-1

This worked for me to capture the token and implement the body of the headers:

Future<List> getData() async {
   final prefs = await SharedPreferences.getInstance();
   final key = 'token';
   final value = prefs.get(key ) ?? 0;
 
   final response = await http.get(Uri.parse("https://tuapi"),  headers: {
   'Content-Type': 'application/json;charset=UTF-8',
   'Charset': 'utf-8',
   "Authorization" : "Bearer $value"
   });
   return json.decode(response.body);

   }
Makyen
  • 31,849
  • 12
  • 86
  • 121