簡體   English   中英

Flutter ListView從嵌套JSON加載數據

[英]Flutter ListView Load Data from Nested JSON

我一直在試圖從一些代碼這個

我正在嘗試從本地JSON加載數據,這個JSON是嵌套模型,這里是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"
                        }
                    ]
                }
            ]
        }
    ]
}

這是我的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;
  }
}

這是我的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(),
        ));
  }
}

我卡住了將類別列表中的JSON數據加載到listview.builder中。

在上面的視圖代碼中,我只想從json列出所有“categoryTitle”,並將ontap動作列入詳細頁面。 怎么做 ?

我已經解決了這個問題,用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,
                        ),
                      )

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

然后我在下面添加以下代碼來加載嵌套的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