【问题标题】:Dart : Unhandled exception: type 'String' is not a subtype of type 'int' of 'index'Dart:未处理的异常:类型'String'不是'index'类型'int'的子类型
【发布时间】:2021-03-22 15:45:35
【问题描述】:

当我使用 ['name'] 从 json http 链接打印名称时,我收到此错误:

Unhandled exception:
type 'String' is not a subtype of type 'int' of 'index'

代码是:

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

void main() {
  print(getData());
}

Future<http.Response?> getData() {
  return http
      .get(Uri.parse("https://jsonplaceholder.typicode.com/users"))
      .then((http.Response response) {
    var a = jsonDecode(response.body)['name'];
    print(a);
  });
}

【问题讨论】:

  • 返回的 JSON 是一个对象列表。直接在这个列表中查询“name”没有任何意义。

标签: http dart asynchronous uri future


【解决方案1】:

您的 JSON 响应采用列表格式。您需要从该列表中选择一个对象才能使用['name'] 选择器。

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

void main() {
  var response = getData();
  for (var person in reponse) {
    print(person['name']);
  }
}

Future<http.Response?> getData() {
  return http
      .get(Uri.parse("https://jsonplaceholder.typicode.com/users"))
      .then((http.Response response) {
    var a = jsonDecode(response.body);
    print(a);

    // Select one of the items here. This case we're selecting the first one.
    var name = a[0]['name'];
    print(name);

    return a;
  });
}

【讨论】:

  • 但是如果我们需要打印每个 id 中的所有名称
  • 我更新了代码。我没有测试它,所以你可能需要稍微调整一下。基本上,响应返回给主函数。在那里,您可以遍历响应项。
  • @MuhammadTawil 这个解决方案对你有用吗?
  • 是的,这项工作,谢谢,但我不知道如何打印每个 id 中的所有名称,但这项工作可以解决这个错误
猜你喜欢
  • 1970-01-01
  • 2021-07-08
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2022-09-22
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多