Formatexception unexpected character at character 1 ошибка

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

I had a same issue and resolve it.

The first issue I got was
«i Found 0 Firebase projects. Selecting project liveasy-1. FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command. COMMAND: firebase —version ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see https://firebase.google.com/docs/cli#install_the_firebase_cli for how to install it.»

and I solved it by

  1. changing the name of firebase-tools-instance.exe to firebase.exe
  2. placing the firebase.exe at the root folder of my flutter project
    The exe file was downloaded from https://firebase.google.com/docs/cli#install-cli-windows
    #reference: https://stackoverflow.com/questions/70410843/firebasecommandexception-an-error-occured-on-the-firebase-cli-when-attempting-t

The next step, I got the same issue with you

C:yp02151_private1_studyappfbtest>dart pub global activate flutterfire_cli
Package flutterfire_cli is currently active at version 0.1.1+2.
Resolving dependencies...
The package flutterfire_cli is already activated at newest available version.
To recompile executables, first run `global deactivate flutterfire_cli`.
Installed executable flutterfire.
Activated flutterfire_cli 0.1.1+2.

C:yp02151_private1_studyappfbtest>flutterfire configure
⠋ Fetching available Firebase projects...
Unhandled exception:
FormatException: Unexpected character (at character 1)
#
^

#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1272:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:937:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:40:10)
#4      JsonDecoder.convert (dart:convert/json.dart:506:36)
#5      runFirebaseCommand (package:flutterfire_cli/src/firebase.dart:95:25)
<asynchronous suspension>
#6      getProjects (package:flutterfire_cli/src/firebase.dart:114:7)
<asynchronous suspension>
#7      ConfigCommand._selectFirebaseProject (package:flutterfire_cli/src/commands/config.dart:159:24)
<asynchronous suspension>
#8      ConfigCommand.run (package:flutterfire_cli/src/commands/config.dart:227:37)
<asynchronous suspension>
#9      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
<asynchronous suspension>
#10     main (file:///C:/Users/yp0215.hong/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutterfire_cli-0.1.1+2/bin/flutterfire.dart:34:5)
<asynchronous suspension>

The solution that I found is run the command of «dart pub global activate flutterfire_cli» and «flutterfire configure» at the firebase shell.

C:yp02151_private1_studyappfbtest>firebase
########################################################################################################################################################################################################################################

     Welcome to...
   ######## #### ########  ######## ########     ###     ######  ########  ##
   ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##        ##
   ######    ##  ########  ######   ########  #########  ######  ######    ##
   ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##       
   ##       #### ##     ## ######## ########  ##     ##  ######  ########  ##
 

########################################################################################################################################################################################################################################

~ Let's make sure your Firebase CLI is ready...
undefined:1



SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at ChildProcess.<anonymous> (C:snapshotfirepitwelcome.js:115:27)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1021:16)
    at Socket.<anonymous> (internal/child_process.js:443:11)
    at Socket.emit (events.js:315:20)
    at Pipe.<anonymous> (net.js:674:12)

> dart pub global activate flutterfire_cli
Package flutterfire_cli is currently active at version 0.1.1+2.
Resolving dependencies...
The package flutterfire_cli is already activated at newest available version.
To recompile executables, first run `global deactivate flutterfire_cli`.
Installed executable flutterfire.
Activated flutterfire_cli 0.1.1+2.

> flutterfire configure
i Found 2 Firebase projects.
? Select a Firebase project to configure your Flutter application with ›
❯ fbtest-6c9d3 (fbtest)

I don’t know it’s the right solution, but I can make the firebase_options.dart file.

My environment is windows10 and I use android studio

»’
C:yp02151_private1_studyappfbtest>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.5.3, on Microsoft Windows [Version 10.0.19042.1415], locale ko-KR)
[√] Android toolchain — develop for Android devices (Android SDK version 31.0.0)
[√] Chrome — develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.63.2)
[√] Connected device (2 available)

• No issues found!

»’

Problem

When sending an HTTP request in Flutter, you may want to decode the JSON response. When doing so, you may encounter the following error:

Flutter FormatException: Unexpected character (at character 1)

This error is caused by the wrong JSON format you get from the response body (e.g. it doesn’t start with an open curly bracket “{“).

Solutions

Printing out the response.body, see the output, and try one of the following solutions:

1. Correct the API endpoint if there is something wrong with it.

2. Provide header information when sending a request:

{
    'Content-Type': 'application/json',
    'Charset': 'utf-8'
}

3. The API may need some auth credentials like username, password, token… Provide them if needed.

4. Maybe the bug isn’t in your Flutter code but on the server side. Review it or communicate with the backend developers in your team.

Hope you’ll get through the annoying problem soon. Further reading:

  • How to encode/decode JSON in Flutter
  • How to read data from local JSON files in Flutter
  • Best Libraries for Making HTTP Requests in Flutter
  • Flutter and Firestore Database: CRUD example
  • Dart: Convert Class Instances (Objects) to Maps and Vice Versa

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

In this post, we are going to show you how to solve «Unexpected character (at character)» error in Flutter/Dart. This error usually happens while decoding an invalid JSON string, or if you are getting invalid JSON from REST API in the Dio package.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═════════════════
The following FormatException was thrown building Builder:
Unexpected character (at character 25)

This error happens when you are decoding invalid JSON with json.decode() or jsonDecode().

I/flutter (16776): DioError [DioErrorType.other]: 
FormatException: Unexpected character (at character 1) I/flutter (16776): <br /> I/flutter (16776): ^ I/flutter (16776): I/flutter (16776): Source stack: I/flutter (16776): #0 DioMixin.fetch (package:dio/src/dio_mixin.dart:473:35) I/flutter (16776): #1 DioMixin.request (package:dio/src/dio_mixin.dart:468:12) I/flutter (16776): #2 DioMixin.get (package:dio/src/dio_mixin.dart:55:12)

This error happens when you are getting invalid JSON data from REST API. You need to remind, that Dio() package returns decoded objects from JSON strings. 

The cause of this error is an invalid JSON string, either JSON string inside code lines or JSON string data fetched from REST API.

Case 1: If you are using jsonDecode() or json.decode() to decode the JSON string, you need to verify if the JSON string is invalid. For example:

String jsonstring = '{"error":false,"msg":"",aa"data":[{"name":"Canada","capital":"Ottawa"}]}';
var jsonobj = jsonDecode(jsonstring); // Runtime Error: Unexpected character (at character)

To solve this error let’s verify if the JSON string is valid or not. You can use any JSON validator. I’m using https://jsonlint.com/ and I got the error like below when validating the JSON.

Error: Parse error on line 3:
...false,	"msg": "",	aa "data": [{		"nam
---------------------^
Expecting 'STRING', got 'undefined'

Its means, I have an invalid JSON string, for example, there is «aa», an unexpected character after «msg» in the JSON string above code.

You can escape this error with try…catch:

try{
 var jsonobj = jsonDecode(jsonstring);
}catch(e){
  print(e);
}

Case 2: If you are fetching JSON string from REST API, or the internet, you may get an error message generated by the compiler in server-side while generating the JSON string. You can use API tester software to check if the REST API is returning valid JSON, For example:

Here, after checking the response from REST API with API tester software, I got the message like below:

This means, we got the error from the server-side, and the error message is returned by REST API along with JSON string. You can resolve this error on a server-side script or, disable the error message on the compiler.

You can escape this error from Dio() like below:

try{
  response = await dio.get(url);
}catch(e){
  print(e);
}

In this way, you can resolve the «Unexpected character (at character)» Error in Flutter/Dart.

Problem Description:

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

Solution – 1

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.

Solution – 2

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.

Solution – 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)

Solution – 4

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

Solution – 5

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

var pdfText= await json.decode(json.encode(response.databody);  

Solution – 6

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);
        });

Solution – 7

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.

Solution – 8

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);

   }

Solution – 9

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

)
)

Solution – 10

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);

}

Solution – 11

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());

Понравилась статья? Поделить с друзьями:
  • Forkplayer ошибка соединения samsung как исправить
  • Forkplayer вследствие внутренней ошибки интернет браузер будет закрыт
  • Forged alliance ошибка при установке
  • Forge of empires ошибка 101
  • Ford transit ошибка двигатель сервис срочно