Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter FormatException: Unexpected character (at character 1)

Tags:

json

http

flutter

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

like image 833
Victor Ortiz Avatar asked Apr 14 '19 02:04

Victor Ortiz


5 Answers

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

var pdfText= await json.decode(json.encode(response.databody);  
like image 81
codingwithtashi Avatar answered Oct 29 '22 16:10

codingwithtashi


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.

like image 35
Victor Ortiz Avatar answered Oct 29 '22 15:10

Victor Ortiz


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'
},

) )

like image 26
Sahil Bansal Avatar answered Oct 29 '22 17:10

Sahil Bansal


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)
like image 42
AdrianFullStack Avatar answered Oct 29 '22 16:10

AdrianFullStack


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.

like image 38
omega_mi Avatar answered Oct 29 '22 17:10

omega_mi