【问题标题】:Parse complex JSON into List Flutter将复杂的 JSON 解析为 List Flutter
【发布时间】:2021-07-20 08:50:08
【问题描述】:

我有一个这样的 json 文件,我存储在资产中:

[
    {
        "topic":"Title One",
        "subTopic":
        [
            "Overview",
            "Install",
            "Start"
        ]
    },
    {
        "topic":"Title Two"
    },
    {
        "topic":"Title Three",
        "subTopic":
        [
            "Overview",
            "Emulation",
            "2. Install"
        ]
    },
    {
        "topic":"Title Four",
        "subTopic":
        [
            "Overview",
            "Start",
            "3. Try"
        ]
    }
]  

其中有一个数组,里面也有数组。我想知道如何将“子主题”解析为列表并显示它。我的班级:

class File {
  String topic;
  List<String> subTopic;

  File({this.topic, this.subTopic});

  File.fromJson(Map<String, dynamic> json) {
    topic = json['topic'];
    subTopic = json['subTopic'];
  }

  Map<String, dynamic> toJson() => {
        'topic': topic,
        'subTopic': subTopic,
      };
}

我在 maint.dart 中做了什么:

class MyHomePage extends StatelessWidget {
  Future<List<File>> getData() async {
    String response = await rootBundle.loadString('file.json');
    return await Future.delayed(Duration(seconds: 2), () {
      List<dynamic> data = jsonDecode(response);
      //Iterate over list and map each object in list
      List<File> files=
          data.map((data) => File.fromJson(data)).toList();
      return files;
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("File"),
        ),
        body: Container(
          child: FutureBuilder<List<File>>(
              future: getData(),
              builder: (context, data) {
                if (data.connectionState != ConnectionState.waiting &&
                    data.hasData) {
                  var fileList = data.data;
                  return Drawer(
                    child: ListView.builder(
                        itemCount: fileList.length,
                        itemBuilder: (context, index) {
                          var fileData = fileList[index];
                          return ExpansionTile(
                            // key: Key("$index"),
                            // title: Text(fileData.topics?? ""),
                            children: <Widget>[
                              Container(
                                width: double.infinity,
                                child: Padding(
                                  padding: const EdgeInsets.all(20.0),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      //I want to display the list of subTopic here
                                    ],
                                  ),
                                ),
                              )
                            ],
                          );
                        }),
                  );
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              }),
        ),
      ),
    );
  }
}

我想在 listView 中显示子主题列表。我怎样才能做到这一点?提前致谢!

【问题讨论】:

  • 您需要将子主题转换为这样的列表 subTopic = json['subTopic'].cast();此外,如果您不确定如何解析 json,请将此作为参考:javiercbk.github.io/json_to_dart
  • @MohammadAssadArshad 我明白了,我怎样才能在列中显示我想要的?

标签: arrays json flutter flutter-web


【解决方案1】:

您可以很容易地将json['subtype'] 转换为Iterable 以生成新的List&lt;String&gt; 对象。

代码:

List<String>.from(json['subTopic'] as Iterable)

完整示例:

class File {
  String topic;
  List<String> subTopic;

  File({this.topic, this.subTopic});

  File.fromJson(Map<String, dynamic> json) {
    topic = json['topic'];
    subTopic = List<String>.from(json['subTopic'] as Iterable);
  }

  Map<String, dynamic> toJson() => {
        'topic': topic,
        'subTopic': subTopic,
      };
}

【讨论】:

    【解决方案2】:

    最好不要从 json 格式的数组映射开始。 也许这就是困难所在。

    enter image description here

    https://app.quicktype.io/

    【讨论】:

      【解决方案3】:

      最好使用Provider和ChangeNotifier,你可以如下更新File类。

      class File {
        String topic;
        List<String> subTopic;
      
        File({this.topic, this.subTopic});
      
        File.fromJson(Map<String, dynamic> json) {
          topic = json['topic'];
          subTopic = (json["subTopic"] as List).map((n) => (n.toString())).toList());
        }
      
        Map<String, dynamic> toJson() => {
              'topic': topic,
              'subTopic': subTopic,
            };
      }
      

      如果需要显示主题和副主题,可以使用flutter_section_table_view

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-29
        • 2021-06-20
        • 2020-04-13
        • 2020-12-21
        • 2020-10-21
        • 1970-01-01
        相关资源
        最近更新 更多