简体   繁体   中英

Converting object to an encodable object failed on api call: _LinkedHashMap len:2

Okay So I am confused as to why I am getting this error. I am trying to make a post request to an api endpoint. Here is my function that passes email and password data to another function that makes the api call

import 'dart:async';
import 'dart:convert';

submit() async {
var res = await LoginAPI().loginData(
    {email: _emailController.value, password: _passwordController.value});
var body = json.decode(res);
print(body);
}

Here is my function that makes the api call.

 import 'package:http/http.dart' as http;

 loginData(data) async {
var fullUrl = _url + "v1/users/login";
  return await http.post(fullUrl, body: jsonEncode(data), headers: _setHeaders());      
}

_setHeaders() => {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
};

When i try to hit that endpoint on postman i get the following data

{
"success": {
  "user": {
        "id": 1,
        "first_name": "Senny",
        "last_name": "Demo",
        "bio": "I am a new bio",
        "email": "senny_demo@gmail.com",
        "phone_number": "081697565335",
        "default_line": "081697565335",
        "balance": 0,
        "lines": [
            {
                "id": 1,
                "user_id": 1,
                "J_Number": "081697565335",
                "account_code": "081697565335",
                "pin": "1234",
                "type": "j_number",
                "created_at": "2019-11-25 13:21:27",
                "updated_at": "2019-11-25 13:21:27"
            }
        ],
        "username": "senny_demo",
        "email_verified": true
    }
}

But on my flutter app i get the following error. Converting object to an encodable object failed: _LinkedHashMap len:2 Any help will be appreciated

I see 2 problems with your code.

  1. You're passing email and password variables as keys of your Map. You should probably make them strings: {'email': _emailController.value, 'password': _passwordController.value}

  2. You're trying to decode whole Response object from json. I guess you wanted you to decode the body of it: var body = json.decode(res.body);

You are trying to do jsonDecode on an Http Response. Try decoding the Response body instead and not the response with res.body . Full code below

import 'dart:async';
import 'dart:convert';

submit() async {
var res = await LoginAPI().loginData(
    {email: _emailController.value, password: _passwordController.value});
var body = json.decode(res.body);
print(body);
}

Secondly, Try putting the Keys in your map in string format like this:

{'email': _emailController.value, 'password': _passwordController.value}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM