flutter 将Json数据显示为列表

xhv8bpkk  于 2023-02-05  发布在  Flutter
关注(0)|答案(2)|浏览(118)

我有一个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());
          }),
    );
  }
}

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

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

当有列表时,我得到了下面的红色下划线错误,代码不会运行。参数类型'List'不能赋给参数类型'Iterable'。
然后,如果我删除为列表,红线消失,但当我运行代码,我得到这个错误在控制台E/flutter(7999):[错误:flutter/运行时/dart_vm_initializer. cc(41)]未处理的异常:类型"List"不是类型"Iterable"的子类型
我知道应用程序正在与服务器正确通信,因为如果我将

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

使用print(names)并运行它,名称将在控制台中打印出来。
任何帮助解决这个问题将不胜感激。干杯

dzjeubhm

dzjeubhm1#

这是你的答案

void convertJsonToList() {

String jsonData = '''
{
  "peoplesnames": [
    "name1",
    "name2",
    "name3",
    "name4",
    "name5",
    "name6",
    "name7",
    "name8"
  ]
}
''';
  Map<String, dynamic> jsonMap = jsonDecode(jsonData);
  peoplesNamesList = List<String>.from(jsonMap['peoplesnames']);
  print(peoplesNamesList);
}
ajsxfq5m

ajsxfq5m2#

试试这个:

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

相关问题