flutterdart

Flutter - Unhandled Exception: FormatException: Unexpected character (at character 1) | Instance of Response


While I'm getting an api, console showing an error like below

E/flutter (10838): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)

E/flutter (10838): Instance of 'Response'

E/flutter (10838): ^

E/flutter (10838):

this is how I'm getting the api

 Future _fetchPost() async {
    http.Response response = await http.get(url);

    if (response.statusCode == 200) {
      print(response.statusCode);
      print(json.decode(response.body));
    } else {
      print(response.statusCode);
    }

    setState(() {
      String jsonsDataString = response.toString();
      _data = jsonDecode(jsonsDataString);
      print(_data.toString());
    });

    return "Success";
  }

status code returns 200 and some of the api

I/flutter (10838): 200

I/flutter (10838): [{restaurant_id: 1010000001, restaurant_name: Cafe, restaurant_image: http://.unicomerp./1010000001.jpg, table_id: 1, table_name: Riyadh-e 01, branch_name: I Cah, nurl: http://snapittaitt.net/api/menu/10/?org=000001&branch_id=100it=10&offset=20&lang=en, table_menu_list: [{menu_category: Salads and Soup, menu_category_id: 11, menu_category_image: http://res.net/iRet/Item/ItemGroup_11.jpg, nexturl: http://snapittappt.net/api/menu/20/?org=1010000001&branch_id=10000001&menuCat=it=10&offset=20&lang=en, category_dishes: [{dish_id: 100001, dish_name: Spinach Salad, dish_price: 7.95, dish_image: http://restaurants.umerp.net///1000000/Items/100000001.jpg, dish_currency: SAR, dish_calories: 15.0, dish_description: Fresh spinach, mushrooms, and hard egg served with warm bacon vinaigrette, dish_Availability: true, dish_Type: 2, nexturl: http://snapitt

E/flutter (10838): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)

E/flutter (10838): Instance of 'Response'

E/flutter (10838): ^

E/flutter (10838):

How can I solve this to achieve getting all api?

Any suggestions would be helpful:)


Solution

  • Change this:

    String jsonsDataString = response.toString(); // Error: toString of Response is assigned to jsonDataString.
    _data = jsonDecode(jsonsDataString);
    print(_data.toString());
    

    To this:

    String jsonsDataString = response.body.toString(); // toString of Response's body is assigned to jsonDataString
    _data = jsonDecode(jsonsDataString);
    print(_data.toString());
    

    I hope this helps, in case of any doubt please comment.