简体   繁体   English

Flutter ListView从嵌套JSON加载数据

[英]Flutter ListView Load Data from Nested JSON

I've been trying some code from this 我一直在试图从一些代码这个

I'm trying to load data from local JSON, this JSON is nested model, here's the JSON. 我正在尝试从本地JSON加载数据,这个JSON是嵌套模型,这里是JSON。

list.json : list.json

{
    "response": "200",
    "categorylist": [
        {
            "categoryId": 1,
            "categoryTitle": "Working",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Working Title",
                    "reference": "Some Working Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        },
        {
            "categoryId": 2,
            "categoryTitle": "Order",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Order Title",
                    "reference": "Some Order Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        }
    ]
}

and here's my list_model.dart : 这是我的list_model.dart

class Category {
  String response;
  List<Categorylist> categorylist;

  Category({this.response, this.categorylist});

  Category.fromJson(Map<String, dynamic> json) {
    response = json['response'];
    if (json['categorylist'] != null) {
      categorylist = new List<Categorylist>();
      json['categorylist'].forEach((v) {
        categorylist.add(new Categorylist.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['response'] = this.response;
    if (this.categorylist != null) {
      data['categorylist'] = this.categorylist.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Categorylist {
  int categoryId;
  String categoryTitle;
  List<CategoryPost> categoryPost;

  Categorylist({this.categoryId, this.categoryTitle, this.categoryPost});

  Categorylist.fromJson(Map<String, dynamic> json) {
    categoryId = json['categoryId'];
    categoryTitle = json['categoryTitle'];
    if (json['categoryPost'] != null) {
      categoryPost = new List<CategoryPost>();
      json['categoryPost'].forEach((v) {
        categoryPost.add(new CategoryPost.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['categoryId'] = this.categoryId;
    data['categoryTitle'] = this.categoryTitle;
    if (this.categoryPost != null) {
      data['categoryPost'] = this.categoryPost.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CategoryPost {
  int postId;
  String postTitle;
  String reference;
  List<PostContent> postContent;

  CategoryPost({this.postId, this.postTitle, this.reference, this.postContent});

  CategoryPost.fromJson(Map<String, dynamic> json) {
    postId = json['postId'];
    postTitle = json['postTitle'];
    reference = json['reference'];
    if (json['postContent'] != null) {
      postContent = new List<PostContent>();
      json['postContent'].forEach((v) {
        postContent.add(new PostContent.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['postId'] = this.postId;
    data['postTitle'] = this.postTitle;
    data['reference'] = this.reference;
    if (this.postContent != null) {
      data['postContent'] = this.postContent.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class PostContent {
  int contentId;
  String author;
  String content;
  String note;
  String explanation;

  PostContent(
      {this.contentId, this.author, this.content, this.note, this.explanation});

  PostContent.fromJson(Map<String, dynamic> json) {
    contentId = json['contentId'];
    author = json['author'];
    content = json['content'];
    note = json['note'];
    explanation = json['explanation'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['contentId'] = this.contentId;
    data['author'] = this.author;
    data['content'] = this.content;
    data['note'] = this.note;
    data['explanation'] = this.explanation;
    return data;
  }
}

here's my view_list.dart : 这是我的view_list.dart

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

  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);    
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }

class Doa extends StatefulWidget {
  Doa({Key key}) : super(key: key);

  _DoaState createState() => _DoaState();
}

class _DoaState extends State<Doa> {

  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

                      ],
                    );
                  }
                )
              ],
            ),
          );
        } 
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        bottom: false,
        child: Scaffold(
        body: futureWidget(),
        ));
  }
}

I'm stuck load the data from JSON inside categorylist into listview.builder. 我卡住了将类别列表中的JSON数据加载到listview.builder中。

in the view code above, I'm only want to list all "categoryTitle" from json, with ontap action to detail page. 在上面的视图代码中,我只想从json列出所有“categoryTitle”,并将ontap动作列入详细页面。 how to do that ? 怎么做 ?

I've solve this problem, write into listviewBuilder with this code inside a widget : 我已经解决了这个问题,用widget中的代码写入listviewBuilder:

  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

                      ],
                    );
                  }
                )
              ],
            ),
          );
        } 
      },
    );
  }

and then I add this code below to load nested json : 然后我在下面添加以下代码来加载嵌套的json:

  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);    
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }

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

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