json in listview flutter
To display JSON data in a ListView in Flutter, you can follow these steps:
First, ensure that you have added the
http
package as a dependency in your pubspec.yaml file.In your Flutter widget, import the necessary packages:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
- Create a model class to represent your JSON data. This class should have properties that match the JSON fields. For example, if your JSON has a "name" field, your model class should have a corresponding "name" property:
class MyData {
final String name;
// Add other properties as needed
MyData({required this.name});
factory MyData.fromJson(Map<String, dynamic> json) {
return MyData(name: json['name']);
}
}
- Inside your Flutter widget, define a function to fetch the JSON data from an API endpoint using the
http
package:
Future<List<MyData>> fetchData() async {
final response = await http.get(Uri.parse('Your API endpoint URL'));
if (response.statusCode == 200) {
List<dynamic> jsonData = jsonDecode(response.body);
List<MyData> data = jsonData.map((json) => MyData.fromJson(json)).toList();
return data;
} else {
throw Exception('Failed to fetch data');
}
}
- In your widget's
initState
method, call thefetchData
function and set the data to a state variable:
List<MyData> _data = [];
@override
void initState() {
super.initState();
fetchData().then((data) {
setState(() {
_data = data;
});
});
}
- Finally, use the ListView.builder widget to display the data in your widget's build method:
ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_data[index].name),
// Display other properties as needed
);
},
)
This code fetches the JSON data from the API endpoint, converts it into a list of MyData
objects using the model class, and then displays it in a ListView using the ListView.builder widget. You can customize the UI as needed to display the other properties of your JSON data.