I have a local JSON file with a 1000 list. How to apply the Lazy Loading or scrollController function in the Listview.builder?
P/S: I have tried this Flutter ListView lazy loading, but I don't know how to modify it. For example: List items = List.generate(100, (position) => 'Hello $position'); how to change this part to the data that loaded from local JSON file?
Below is post.json file
{
"Food": [
{
"name": "Cake",
"id": "0001",
"description": [
{
"category": "AAA",
"Size": "Regular",
"topping": "Chocolate with Sprinkles"
},
{
"category": "AAA",
"Size": "Small",
"topping": "Chocolate only"
},
{
"category": "BBB",
"Size": "Regular",
"topping": "Maple"
},
{
"category": "BBB",
"Size": "Small",
"topping": "Blueberry"
},
{
"category": "CCC",
"Size": "Medium",
"topping": "Strawberry"
},
{
"category": "CCC",
"Size": "small",
"topping": "banana"
},
{
....another 1000 list
}
]
},
{
"name": "Raised",
"id": "0002",
"description": ... // same structure as above
}
]
}
Below is the Main file
void main() {
runApp(const MyApp());
}
// Load local Json file
Future<Post> getFoodList () async {
final getResponse = await rootBundle.loadString('assets/post.json');
var data = jsonDecode(getResponse);
return Post.fromJson(data);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: FutureBuilder<Post>(
future: getFoodList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var getFoodName = snapshot.data!.food;
return SingleChildScrollView(
child: Wrap(
children: [
for (final food in getFoodName!)
GestureDetector(
child: Text(foodName.name.toString()),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => foodDetail(food: food)));
},
),
],
),
);
} else {
return Text('Loading');
}
},
),
),
],
),
);
}
}
Below is the food detail page. As there will be a 1000 lists of food details, how do I apply lazy loading, scrollController?
class FoodDetail extends StatefulWidget {
final Food food;
const FoodDetail({super.key, required this.food});
@override
State<FoodDetail> createState() => _FoodDetailState();
}
class _FoodDetailState extends State<FoodDetail> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
children: [
ListView.builder(
itemCount: widget.food.description!.length,
itemBuilder: (context, index) {
return Column(
children: [
Text(widget.food.description![index].category.toString())
Text(widget.food.description![index].topping.toString())
],
);
}
),
],
),
)));
}
}