'Small fix on expansion tile with json data
I have a complex json. Using it must create expansion tiles. Imagine that in categories there are subcategories. In subcategories also have sub-sub categories. But model is same. I created that, but in Entry.fromJson() method need a small fix on children. I can't get child subcategories of categories. Please not use any plugin like flutter_treeview . Please help. Sample json string is in below:
[{"id":1,"name":"parent 1","subcategories":[{"id":11,"name":"cat news 1 of 1","subcategories":[]}]},{"id":2,"name":"parent 2","subcategories":[{"id":22,"name":"cat news 1 of 2","subcategories":[]}]},{"id":3,"name":"parent 3","subcategories":[]}]
The flutter code shown below:
class SubcategoryPage2 extends StatefulWidget {
const SubcategoryPage2({Key? key}) : super(key: key);
@override
_SubcategoryPage2State createState() => _SubcategoryPage2State();
}
class _SubcategoryPage2State extends State<SubcategoryPage2> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('2nd test')),
body: ListView.builder(
itemCount: jsonDecode(sampleJson)[0].length,
itemBuilder: (context, int index) =>
EntryItem(Entry.fromJson(jsonDecode(sampleJson)[index])),
),
);
}
}
class Entry {
final int id;
final String name;
final List<Entry> children;
Entry(
{required this.id, required this.name, this.children = const <Entry>[]});
factory Entry.fromJson(Map<String, dynamic> json) {
return Entry(
id: json['id'],
name: json['name'],
children: List<Entry>.from(json['subcategories'])
);
}
}
class EntryItem extends StatelessWidget {
final Entry entry;
const EntryItem(this.entry, {Key? key}) : super(key: key);
Widget _buildTiles(Entry root) {
if (root.children.isEmpty) {
return ListTile(title: Text(root.name));
}
return ExpansionTile(
key: PageStorageKey<Entry>(root),
title: Text(root.name),
children: root.children.map(_buildTiles).toList(),
);
}
@override
Widget build(BuildContext context) {
return _buildTiles(entry);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
