【问题标题】:displaying Json data as a list将 Json 数据显示为列表
【发布时间】:2023-02-03 20:26:42
【问题描述】:

我有一个 json 文件,我试图在我的应用程序中显示为列表。 这是 json 文件及其布局方式:

{
  "peoplesnames": [
    "name1",
    "name2",
    "name3",
    "name4",
    "name5",
    "name6",
    "name7",
    "name8"
  ]
}

这是我的应用程序中的代码:

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

class test extends StatefulWidget {
  const test({Key? key}) : super(key: key);

  @override
  State<test> createState() => _testState();
}

class _testState extends State<test> {
  List<String> peopleNames = [];

  void getData() async {
    http.Response response = await http.get(
      Uri.parse('www.genericwebsite.com'),
    );
    if (response.statusCode == 200) {
      String data = response.body;
      final names = jsonDecode(data);
      peopleNames.addAll((names['peoplesnames'] as List));
      setState(() {});
      return names;
    } else {
      print(response.statusCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold(
      body: ListView.builder(
          shrinkWrap: true,
          itemCount: peopleNames.length,
          itemBuilder: (context, index) {
            return Text(peopleNames[index].toString());
          }),
    );
  }
}

问题似乎来自以下代码行中的列表:

peopleNames.addAll((names['peoplesnames'] as List));

当 List 在那里时,我收到以下红色下划线错误,代码将无法运行。 不能将参数类型“List”分配给参数类型“Iterable”。

然后,如果我作为列表删除,红线消失但是当我运行代码时,我在控制台中收到此错误 E/flutter (7999): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:类型“List”不是类型“Iterable”的子类型

我知道该应用程序正在与服务器正确通信,因为如果我更换

peopleNames.addAll((names['peoplesnames'] as List));
setState(() {});
return names;

使用 print(names) 并运行它,名称会打印在控制台中。

任何解决此问题的帮助将不胜感激。 干杯

【问题讨论】:

    标签: json flutter


    【解决方案1】:

    尝试这个:

    peopleNames.addAll((names['peoplesnames'].toList()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2020-10-23
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多