Home > database >  displaying Json data as a list
displaying Json data as a list

Time:02-04

I have a json file that i'm trying to display as a list in my app. here is the json file and how it is laid out:

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

and here is the code from my app:

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());
          }),
    );
  }
}

The problem seems to be coming from as List in the following line of code:

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

when as List is there I get the followiing red underline error and the code won't run. The argument type 'List' can't be assigned to the parameter type 'Iterable'.

then, If i remove as List, the red line goes away but when I run the code, i get this error in the console E/flutter ( 7999): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List' is not a subtype of type 'Iterable'

I know the app is talking to the server correctly because if i replace

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

with print(names), and run it, the names print in the console.

any help fixing this would be greatly appreciated. cheers

CodePudding user response:

Here is your answer

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);
}

CodePudding user response:

Try this:

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