Home > Software design >  How to display a nested json file in listview in Flutter
How to display a nested json file in listview in Flutter

Time:11-30

i'm learning flutter recently, and i have a problem. How display nested json file in listview in flutter ?

On internet i see a lots of example but it's with an url of an api and i don't want use api. I'm in local.

I think the problem is not my parse, but i don't know so, below you can see my code.

array.json


[
  {
    "jp": {
      "name": "jp",
      "password": "pawwordTest",
      "maxtun": 0,
      "email": "[email protected]",
      "date": {
        "build": "test1",
        "first_cnx": "test2"
      }
    }
  }
]

array.dart

class JP {
  final String name;
  final String password;
  final int maxtun;
  final String email;
  final Date date;


  JP({
    required this.name,
    required this.password,
    required this.maxtun,
    required this.email,
    required this.date,

  });

  factory JP.fromJson(Map<String, dynamic> json){
    return JP(
      name: json['name'],
      password: json['password'],
      maxtun: json['maxtun'],
      email: json['email'],
      date: Date.fromJson(json['date']),

    );
  }
}

class Date{
  final String build;
  final String firstCNX;

  Date({required this.build, required this.firstCNX});

  factory Date.fromJson(Map<String, dynamic> json){
    return Date(
      build: json['build'],
      firstCNX: json['first_cnx']
    );
  }
}


And event_page.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'dart:async' show Future;
//import 'package:flutter/material.dart' show rootBundle;
import 'package:array_json/array.dart';
import 'package:flutter/services.dart';

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

  @override
  State<EventPage> createState() => _EventPageState();
}

class _EventPageState extends State<EventPage> {

  List<JP> testJson = [];

  Future<void> readJson() async{
    final String response = await rootBundle.loadString("assets/array.json");
    final informationData = await json.decode(response);

    var list = informationData['jp'] as List<dynamic>;

    setState(() {
      testJson = [];
      testJson = list.map((e) => JP.fromJson(e)).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leadingWidth: 100,
        leading: ElevatedButton.icon(
          onPressed: () => Navigator.of(context).pop(),
          icon: const Icon(Icons.arrow_back_ios,
            color: Colors.blue,
          ),
          label: const Text("Back",
            style: TextStyle(color: Colors.blue),
          ),
          style: ElevatedButton.styleFrom(
            elevation: 0,
            backgroundColor: Colors.transparent,
          ),
        ),
        centerTitle: true,
        title: const Text("Load and Read JSON File",
          style: TextStyle(color: Colors.black54),
        ),
        backgroundColor: Colors.white,
      ),
      body: Column(
        children: [
          Padding(padding: EdgeInsets.all(15.0),
          child: ElevatedButton(onPressed: readJson,
          child: const Text("Load Informations")),
          ),
          Expanded(
              child: ListView.builder(
                  itemCount: testJson.length,
                  itemBuilder: (BuildContext context, index){
                    final x = testJson[index];
                    return Container(
                      padding: EdgeInsets.all(10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text("test : ${x.name}"),
                          Text(x.password),
                          Text(x.maxtun.toString()),
                          Text(x.email),
                          const SizedBox(
                            height: 5.0,
                          ),
                          const Text("Date : ",
                            style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                          ),
                          Text(x.date.build),
                          Text(x.date.firstCNX),
                          const SizedBox(
                            height: 5.0,
                          ),
                        ],
                      ),
                    );
                  }
              ),
          ),
        ],
      ),
    );
  }
}

Help me please, i'm sure, i'm not missing much but it's the question

CodePudding user response:

informationData['jp'] can't be a List, it's a Map, try this code instead:

Future<void> readJson() async{
  final String response = await rootBundle.loadString("assets/array.json");
  final informationData = json.decode(response) as List;

  setState(() {
    testJson = informationData.map<JP>((e) => JP.fromJson(e['jp'])).toList();
  });
}

CodePudding user response:

actually the problem you have is that the json file has a list and you are accessing it like map so that is causing issue change your json file content with this that will solve your problem

{
"jp": [
    {
        "name": "jp",
        "password": "pawwordTest",
        "maxtun": 0,
        "email": "[email protected]",
        "date": {
            "build": "test1",
            "first_cnx": "test2"
        }
    }
]
}
  • Related