英文:
Flutter filtering Json data
问题
我有一个JSON数据,我想要筛选并获取具有特定值的数据。首先,我获取了JSON数据并将其存储在一个列表中。
List _amh = [];
Future<void> readAmh() async {
final String response = await rootBundle.loadString('assets/json/amh.json');
final data = await json.decode(response);
setState(() {
_amh = data["items"];
});
}
所以JSON数据如下所示:
{
"items": [
{
"chapter": 1,
"verse": 1,
"text": "Lorem Ipsum ....."
},
{
"chapter": 1,
"verse": 2,
"text": "Lorem Ipsum ....."
},
{
"chapter": 1,
"verse": 3,
"text": "Lorem Ipsum ....."
},
....
{
"chapter": 2,
"verse": 1,
"text": "Lorem Ipsum ....."
},
{
"chapter": 2,
"verse": 2,
"text": "Lorem Ipsum ....."
},
...
]
}
所以我想要的是,当用户选择第一章时,我想要显示与该章相关的数据。我该如何做到这一点?
英文:
I have a json data which i wan t to filter and get data that has specific value. first i got the json data and store it in a list.
List _amh = [];
Future<void> readAmh() async {
final String response = await rootBundle.loadString('assets/json/amh.json');
final data = await json.decode(response);
setState(() {
_amh = data["items"];
});
}
so the json data looks like
{
"items": [
{
"chapter": 1,
"verse": 1.
"text": "Lorem Ipsum ....."
},
{
"chapter": 1,
"verse": 2.
"text": "Lorem Ipsum ....."
},
{
"chapter": 1,
"verse": 3.
"text": "Lorem Ipsum ....."
},
....
{
"chapter": 2,
"verse": 1.
"text": "Lorem Ipsum ....."
},
{
"chapter": 2,
"verse": 2.
"text": "Lorem Ipsum ....."
},
...
]
}
so what i wanted is that when the user selects chapter one, i wanted to display the data related to that chapter. how can i do that?
答案1
得分: 1
你可以可能使用以下代码:
List
return _amh.where((item) => item["chapter"] == chapter).toList();
}
**编辑:**
假设 `_selectedChapter = 1`,你可以使用 `ListView` 来显示 `text`:
body: ListView.builder(
itemCount: getChapterData(_selectedChapter).length,
itemBuilder: (BuildContext context, int index) {
final verse = getChapterData(_selectedChapter)[index];
return ListTile(
title: Text('Verse ${verse["verse"]}'),
subtitle: Text(verse["text"]),
);
},
),
);
<details>
<summary>英文:</summary>
You could possibly use
List<dynamic> getChapterData(int chapter) {
return _amh.where((item) => item["chapter"] == chapter).toList();
}
**Edit:**
Assuming the `_selectedChapter = 1` , you can use `ListView` to display the `text`
body: ListView.builder(
itemCount: getChapterData(_selectedChapter).length,
itemBuilder: (BuildContext context, int index) {
final verse = getChapterData(_selectedChapter)[index];
return ListTile(
title: Text('Verse ${verse["verse"]}'),
subtitle: Text(verse["text"]),
);
},
),
);
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论