【问题标题】:How to display a nested json file in listview in Flutter如何在 Flutter 的列表视图中显示嵌套的 json 文件
【发布时间】:2022-11-30 02:38:46
【问题描述】:

最近在学flutter,遇到了问题。如何在 flutter 的列表视图中显示嵌套的 json 文件?

在互联网上我看到了很多例子,但它有一个 api 的 url,我不想使用 api。我在当地。

我认为问题不是我的解析,但我不知道,下面你可以看到我的代码。

数组.json


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

数组.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']
    );
  }
}


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

请帮助我,我敢肯定,我并没有错过太多,但这是问题所在

【问题讨论】:

  • 你有什么错误吗?
  • 我没有错误:/
  • 那么你面临的问题是什么?
  • 我想在列表视图中显示我的 json 文件,我有一个包含不同项目的列表视图,但没有显示任何内容

标签: json flutter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多