【问题标题】:Flutter. When copy List to List got error扑。将列表复制到列表时出错
【发布时间】:2021-08-12 14:33:16
【问题描述】:

我想将带有 hostId 值的列表数据从 Json 复制到空列表 pcBusy。我写了代码,但我得到了错误 "_TypeError (type 'int' is not a subtype of type 'List')".

感谢您的帮助!)

List pcBusy = [];

void fetchDataStandart() async {
  final urlAuth =
      Uri.parse('http://185.XX.XXX.XXX/api/usersessions/activeinfo');
  final response = await http
      .get(urlAuth, headers: <String, String>{'authorization': basicAuth});

  if (response.statusCode == 200) {
    List listPc = List.from(json.decode(response.body)['result']);

    for (int i = 0; i < listPc.length; i++) {
      pcBusy = listPc[i]['hostId'];
    }
    print(pcBusy);
  } else {
    throw Exception('Ошибка получения данных');
  }
}

【问题讨论】:

  • 你的返回值是int,所以不能赋值给列表,尝试打印List.from(json.decode(response.body)['result'])或者json.decode( response.body)['result'] 看看它打印了什么。

标签: json dart


【解决方案1】:

您需要调用.add() 方法将元素添加到List(您正在做的是使用=int 分配给您的pcBusy 变量,这会导致错误,因为int不是List,并且你不能在 Dart 中更改运行时变量的类型):

List<int> pcBusy = [];

void fetchDataStandart() async {
  final urlAuth =
      Uri.parse('http://185.XX.XXX.XXX/api/usersessions/activeinfo');
  final response = await http
      .get(urlAuth, headers: <String, String>{'authorization': basicAuth});

  if (response.statusCode == 200) {
    List listPc = List.from(json.decode(response.body)['result']);

    for (int i = 0; i < listPc.length; i++) {
      pcBusy.add(listPc[i]['hostId'] as int);
    }
    print(pcBusy);
  } else {
    throw Exception('Ошибка получения данных');
  }
}

我还尝试添加一些最少的输入。一般来说,除非你真的想要List&lt;dynamic&gt;,否则不要使用List

【讨论】:

  • 嗨!如何更新代码以通过添加新值来刷新 pcBusy 列表,而不仅仅是添加值。当我点击两次时,这是打印“I/flutter (17340): [S14, S18, S19, S12, S14, S18, S19, S12]”。
  • 您可以尝试使用Set&lt;int&gt;,而不是List&lt;int&gt;Set 不能包含重复值。
猜你喜欢
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
相关资源
最近更新 更多