简体   繁体   English

如何在Flutter的listview中显示嵌套的json文件

[英]How to display a nested json file in listview in Flutter

i'm learning flutter recently, and i have a problem.最近在学习flutter,遇到了问题。 How display nested json file in listview in flutter?如何在flutter的listview中显示嵌套的json文件?

On inte.net 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.在 inte.net 上,我看到了很多示例,但它带有 url 和 api,我不想使用 api。我在本地。

I think the problem is not my parse, but i don't know so, below you can see my code.我认为问题不是我的解析,但我不知道,下面你可以看到我的代码。

array.json阵列.json


[
  {
    "jp": {
      "name": "jp",
      "password": "pawwordTest",
      "maxtun": 0,
      "email": "jp@france.fr",
      "date": {
        "build": "test1",
        "first_cnx": "test2"
      }
    }
  }
]

array.dart数组.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和 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请帮助我,我敢肯定,我并没有错过太多,但这是问题所在

informationData['jp'] can't be a List , it's a Map , try this code instead: informationData['jp']不能是List ,它是Map ,试试这个代码:

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

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实际上你遇到的问题是 json 文件有一个列表,你正在像 map 一样访问它,所以这会导致问题改变你的 json 文件内容,这将解决你的问题

{
"jp": [
    {
        "name": "jp",
        "password": "pawwordTest",
        "maxtun": 0,
        "email": "jp@france.fr",
        "date": {
            "build": "test1",
            "first_cnx": "test2"
        }
    }
]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM