将json数据解码为列表以在listView中显示

qmelpv7a  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(111)

我有一个简单的Json文件(名称列表),需要在ListView小部件中显示其中的数据:

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

我在一个有状态小部件中创建了getter,如下所示:

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> {
  
  void getData() async {
    http.Response response = await http.get(
      Uri.parse('www.genericwebsite.com'),
    );
    if (response.statusCode == 200) {
      String data = response.body;
      var names = jsonDecode(data)['names'];
      print(names);
      return names;
    } else {
      print(response.statusCode);
    }
  }
  
  
  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold(
      body: ListView(children: [
        
      ],),
    );
  }
}

当我运行这段代码时,它工作了!我可以看到控制台中打印的名称。
我现在需要的是关于please的帮助,将数据转换成列表,然后让它显示在listView小部件中。我在之前的帖子中被告知使用Listnames = awaitgetData;但是无论我把它放在代码的什么地方,它都会抛出错误。
非常感谢你的时间和耐心。干杯

egdjgwm8

egdjgwm81#

你可以做以下事情

class _testState extends State<test> {
 //Creating List Variable with empty list
 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);
      print(names); //
      peopleNames.addAll((List<String>.from(names['peoplesnames']));//If and only if this is 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());
         }
      ),
    );
  }
}

相关问题