首页 > 解决方案 > api 调用将对象转换为可编码对象失败:_LinkedHashMap len:2

问题描述

好的所以我很困惑为什么我会收到这个错误。我正在尝试向 api 端点发出发布请求。这是我的函数,它将电子邮件和密码数据传递给另一个进行 api 调用的函数

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

这是我进行 api 调用的函数。

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

当我尝试在邮递员上击中那个端点时,我得到以下数据

{
"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
    }
}

但是在我的颤振应用程序上,我收到以下错误。将对象转换为可编码对象失败:_LinkedHashMap len:2 任何帮助将不胜感激

标签: flutter

解决方案


我发现您的代码有 2 个问题。

  1. 您将电子邮件和密码变量作为 Map 的键传递。您可能应该将它们设为字符串:{'email': _emailController.value, 'password': _passwordController.value}

  2. 您正在尝试从 json解码整个Response对象。我猜你想让你解码它的主体:var body = json.decode(res.body);


推荐阅读