json.decode() Unexpected end of input (at character 1)
Asked Answered
L

8

29

I am facing a anonymus closure error in flutter while signing in a user. It worked a few days before but now its not working, I dont no why. So please help and thanks in advance..Whenever i fill the details and tap on the signin button it throws the below error---

E/flutter ( 2914): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 2914): FormatException: Unexpected end of input (at character 1)
E/flutter ( 2914): 
E/flutter ( 2914): ^
E/flutter ( 2914): 
E/flutter ( 2914): #0      _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)
E/flutter ( 2914): #1      _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:511:7)
E/flutter ( 2914): #2      _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10)
E/flutter ( 2914): #3      JsonDecoder.convert (dart:convert/json.dart:540:36)
E/flutter ( 2914): #4      JsonCodec.decode (dart:convert/json.dart:167:41)
E/flutter ( 2914): #5      _SignInState._login.<anonymous closure> (package:restaurant_app/signin.dart:81:23)
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:restaurant_app/globalVar.dart';
import 'package:restaurant_app/homescreen.dart';
 import 'package:flutter_secure_storage/flutter_secure_storage.dart';
 import 'package:restaurant_app/signup.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_html_view/html_parser.dart';

class SignIn extends StatefulWidget {
 @override
_SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> with SingleTickerProviderStateMixin 
{
TabController controller;
TextEditingController _email = new TextEditingController();
TextEditingController _password = new TextEditingController();
bool loading;

 final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState> 
();

@override
void initState() {
// TODO: implement initState
super.initState();
controller = new TabController(length: 2, vsync: this);
loading = false;
_email = new TextEditingController(text: "rajeshvishnani");
_password = new TextEditingController(text: "Rajesh@MaaKiRasoi");
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
controller.dispose();
setState(() {
  loading = false;
});
_email.dispose();
_password.dispose();
}

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool _autoValidate = false;

Future _writer(String username, String password, String token) async {
final storage = new FlutterSecureStorage();
await storage.write(key: authTokenKeys, value: token);
print(await storage.read(key: authTokenKeys));
await storage.write(key: nameKeys, value: username);
print(await storage.read(key: nameKeys));
await storage.write(key: passwordKeys, value: password);
}

  static final String authTokenKeys = 'auth_token';
static final String nameKeys = 'username';
static final String passwordKeys = 'password';

_login(username, password) async {
setState(() {
  loading = true;
});

var body = json.encode({
  "username": username,
  "password": password,
});

Map<String, String> headers = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
};

await http
    .post("${GlobalVar.Ip}/wp-json/jwt-auth/v1/token",
        body: body, headers: headers)
    .then((response) {
  var body = json.decode(response.body);

  if (response.statusCode == 200) {
    // TODO: you need to store body['token'] to use in some authentication
    loading = false;
    _writer(_email.text, _password.text, body['token']);
    Navigator.pushReplacement(context,
        MaterialPageRoute(builder: (BuildContext ctx) => HomePage()));
  } else {
    // TODO: alert message
    final snackBar = SnackBar(
      content: Text(body['message']),
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);
  }
  setState(() {
    loading = false;
  });
  });
}

@override
 Widget build(BuildContext context) {
return Scaffold(
  key: _scaffoldKey,
  resizeToAvoidBottomPadding: false,
  body: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('images/art.png'),
        fit: BoxFit.fill,
        colorFilter: ColorFilter.mode(
            Colors.white12.withOpacity(0.2), BlendMode.dstATop),
      ),
    ),
    child: ListView(
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Align(
          alignment: Alignment.topCenter,
          child: CircleAvatar(
            backgroundColor: Colors.grey,
            radius: 55.0,
            backgroundImage: AssetImage('images/logo.png'),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).size.height / 300,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Row(
              children: <Widget>[
                SizedBox(
                  width: MediaQuery.of(context).size.width / 4,
                ),
                Chip(
                  label: Text(
                    "SIGN IN",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Color(0xFFD1A155),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width / 35,
                  child: Container(
                    width: MediaQuery.of(context).size.height / 12,
                    height: 2.0,
                    color: Colors.white,
                  ),
                ),
                Chip(
                  label: Text(
                    "SIGN UP",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Colors.black87,
                ),
              ],
            )
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 35,
        ),
        Align(
            alignment: Alignment.center,
            child: Text(
              "Welcome back!",
              style: TextStyle(
                fontSize: 20.0,
                color: Color(0xFFD1A155),
              ),
            )),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Form(
          key: _formKey,
          autovalidate: _autoValidate,
          child: Column(
            children: <Widget>[
              Theme(
                data: ThemeData(
                  hintColor: Colors.black26,
                  primaryColor: Color(0xFFD1A155),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.emailAddress,
                    //validator: _email.text.isEmpty?:null,
                    controller: _email,

                    decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.email,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Email Address',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height / 45,
              ),
              Theme(
                data: ThemeData(
                    primaryColor: Color(0xFFD1A155),
                    hintColor: Colors.black26),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    obscureText: true,
                    controller: _password,
                  decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.lock,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Password',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 15.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        ActionChip(
                          onPressed: () {},
                          avatar: Checkbox(
                            value: false,
                            onChanged: (bool z) {
                              print(z);
                            },
                            activeColor: Color(0xFFD1A155),
                          ),
                          label: Text("Remember Me"),
                          backgroundColor: Colors.transparent,
                        ),
                      ],
                    ),
                    Text(
                      "Forgot Password?",
                      style: TextStyle(
                        color: Color(0xFFD1A155),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                child: InkWell(
                  onTap: () {
                    _login(_email.text, _password.text);
         //                        Navigator.push(
        //                            context,
    //                            MaterialPageRoute(
     //                                builder: (context) => HomePage()));
                  },
                  child: loading
                      ? CircularProgressIndicator()
                      : Container(
                          height: MediaQuery.of(context).size.height / 13,
                          //width: MediaQuery.of(context).size.height / 1.8,
                          decoration: BoxDecoration(
                            color: Color(0xFFD1A155),
                            borderRadius: BorderRadius.circular(5.0),
                          ),
                          child: Center(
                            child: Text(
                              "LOGIN",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 18.0),
                            ),
                          ),
                        ),
                ),
              )
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 15,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: 2.0,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height / 18,
              width: MediaQuery.of(context).size.height / 11,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(23.0),
                  color: Colors.white,
                  border: Border.all(color: Colors.black12)),
              child: Center(
                  child: Text(
                "OR",
                style: TextStyle(fontSize: 18.0),
              )),
            ),
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15.0, right: 15.0),
          child: Row(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.2,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Facebook",
                      style: TextStyle(fontSize: 22.0, color: Colors.blue),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width / 40,
              ),
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.3,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Google+",
                      style: TextStyle(fontSize: 22.0, color: Colors.red),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 20,
        ),
        Align(
          alignment: Alignment.center,
          child: InkWell(
            onTap: () => Navigator.push(
                context, MaterialPageRoute(builder: (context) => SignUp())),
            child: RichText(
                text: TextSpan(
                    text: "Don't have an account?",
                    style: TextStyle(fontSize: 20.0, color: Colors.black87),
                    children: <TextSpan>[
                  TextSpan(
                      text: ' Sign up',
                      style: TextStyle(
                          color: Color(0xFFD1A155),
                          fontWeight: FontWeight.bold)),
                ])),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
      ],
    ),
  ),
  );
 }
}
Leaper answered 31/1, 2019 at 17:59 Comment(10)
"anonymous closure" is the least relevant part of the error. response.body - the value you pass to json.decode(...) is not valid JSON. Already the first character is invalid - probably it's just null.Currie
The "anonymous closure" comes from then(...) where you pass an anonymous closure that calls json.decode() and is shown as first stack frame in the exception output. Because the passed closure (or function) does not have a name like for example _login it is listed as "anonymous closure".Currie
Then what should I do to solve the error?Leaper
Figure out what value you get from response.bodyCurrie
I tried to print response.body but nothing came...Leaper
what do you mean by "nothing came"? before var body = json.decode(response.body); call print('body: [${response.body}]');Jaco
Perhaps it's an empty string ""Currie
@Bishal Das, how did you fix your problem? I'm facing same one... #55367768Champion
I think there is a syntax error in your JSON, use jsonlint.com to check for syntax errors.Berny
i get this error even though the app runs fine without issue. Its like theres a delay in reading the results or somethingSupersensual
A
29

I also have similar type of error, Be make sure that the argument of .decode method shouldn't be empty object. Instead of using this line:

var body = json.decode(response.body);

Try

if(response.body.isNotEmpty) {
    json.decode(response.body);
}

Do try this, hope it will work for you.

Audible answered 25/5, 2020 at 19:15 Comment(1)
This helped me in debugging, my problem was in the backend, the response was wrong, it was fixed there and it worked.Polypeptide
C
4

Print your body and double check you aren't trying to decode an array rather than on object.

Christman answered 2/6, 2020 at 16:35 Comment(1)
This! Second time I am getting caught out by this. I have a query that returns a single object and I was treating it like an array.Pierian
T
1

check your backend it return null object in the response body

Tendril answered 11/4, 2022 at 11:14 Comment(0)
S
1

I was able to fix this error by adding .trim()

     if (response.statusCode == 200) {
        final responseBody = response.body.trim(); 
       if (responseBody.isNotEmpty) {
       } else {};

When using jsonDecode or json.decode, it expects a valid JSON response even if it's an empty json object or array. The .trim() function removes any blank response from your API and convert it to an empty json data.

Lets say you are sending an http request to Create, Update or Delete data from your database but your API does not return any jsonData value such as echo json_encode("Successful");

This was my case. The decode function treated the response as a not-valid json response. You either need to trim it and decode only if the response is not empty, or modify your API to send some kind of response no matter what operation it is doing.

Supersensual answered 4/9, 2023 at 17:17 Comment(0)
R
0

I had similar type of problem, i tried everything but eventually the problem was that I was using http intead of using https even though the apis was in https, i forgot to add s at in http. After changing to https from http the error was gone.

Rhombus answered 22/7, 2020 at 16:51 Comment(0)
P
0

Please check your header in http or dio in flutter

  headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    }
Patriarchate answered 10/5, 2023 at 13:24 Comment(0)
L
0

Please Check You Header If you are Sending Jwt Token

Ligure answered 21/7, 2023 at 15:53 Comment(0)
H
0

I ran into this issue because the response.body was empty -- which, after checking if the body was empty as mentioned by Parag above, led to another occasional issue (Unhandled Exception: FormatException: Unexpected extension byte (at offset 5))

The response.body was empty because the PHP script was not echoing the result because it could not json_encode it. The reason this occurred is because it could not encode some characters in certain rows in the database.

The fix was as such in the PHP script:

// Connect to the MySQL database
$conn = new mysqli($host, $user, $password, $database);
// Set the charset to utf-8
$conn->set_charset("utf8");

This set the character set to "utf-8" and the data was able to be encoded and echoed after.

Harvell answered 19/10, 2023 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.