【发布时间】: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