📱 Flutter ListView.builder with JSON Data
ListView.builder is a powerful way to build scrollable lists in Flutter dynamically. In this tutorial, we will use JSON data directly inside our app (i.e., not from an API) and display it in a scrollable list.
✅ This is useful for apps that have bundled JSON assets or local data you want to test before integrating APIs.
🔹 Sample JSON Data
{
"students": [
{ "name": "Ravi", "age": 21 },
{ "name": "Sneha", "age": 20 },
{ "name": "Arjun", "age": 22 },
{ "name": "Meera", "age": 19 }
]
}
🔹 Step 1: Add JSON to the Dart file
Normally, you load a JSON file, but here we're hardcoding it as a Dart object for simplicity.
// main.dart
final String jsonData = '''
{
"students": [
{ "name": "Ravi", "age": 21 },
{ "name": "Sneha", "age": 20 },
{ "name": "Arjun", "age": 22 },
{ "name": "Meera", "age": 19 }
]
}
''';
🔹 Step 2: Parse the JSON
import 'dart:convert';
List students = [];
void loadJson() {
Map parsed = jsonDecode(jsonData);
students = parsed['students'];
}
🔹 Step 3: Use ListView.builder
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Student List')),
body: ListView.builder(
itemCount: students.length,
itemBuilder: (context, index) {
final student = students[index];
return ListTile(
leading: CircleAvatar(child: Text(student['name'][0])),
title: Text(student['name']),
subtitle: Text('Age: ${student['age']}'),
);
},
),
);
}
🎯 Full Example
import 'package:flutter/material.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListView with JSON',
home: StudentListScreen(),
);
}
}
class StudentListScreen extends StatefulWidget {
@override
_StudentListScreenState createState() => _StudentListScreenState();
}
class _StudentListScreenState extends State<StudentListScreen> {
final String jsonData = '''
{
"students": [
{ "name": "Ravi", "age": 21 },
{ "name": "Sneha", "age": 20 },
{ "name": "Arjun", "age": 22 },
{ "name": "Meera", "age": 19 }
]
}
''';
List students = [];
@override
void initState() {
super.initState();
final parsed = jsonDecode(jsonData);
students = parsed['students'];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Student List')),
body: ListView.builder(
itemCount: students.length,
itemBuilder: (context, index) {
final student = students[index];
return ListTile(
leading: CircleAvatar(child: Text(student['name'][0])),
title: Text(student['name']),
subtitle: Text('Age: ${student['age']}'),
);
},
),
);
}
}
🧠Why use ListView.builder?
- Efficient memory usage – widgets are built only when visible
- Supports large datasets
- Custom UI for each item
📚 Wrap Up
Using ListView.builder
in Flutter with JSON is simple and effective. Whether you're testing local data or integrating APIs later, mastering this technique will help you build dynamic and scrollable lists with ease.
0 Comments