how to display data from json api using flutter expansiontile
To display data from a JSON API using Flutter's ExpansionTile widget, you can follow these steps:
- Make sure you have the necessary dependencies added to your
pubspec.yaml
file. You will need thehttp
package to make API requests and theflutter_spinkit
package for loading indicators. Here is an example of how to add these dependencies:
dependencies:
flutter:
sdk: flutter
http: ^0.13.4
flutter_spinkit: ^5.1.0
- Import the necessary packages in your Dart file:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
- Create a class to represent the data you will receive from the API. This class should have properties that match the JSON structure. For example:
class MyData {
final String title;
final List<String> items;
MyData({required this.title, required this.items});
factory MyData.fromJson(Map<String, dynamic> json) {
return MyData(
title: json['title'],
items: List<String>.from(json['items']),
);
}
}
- Create a stateful widget that will fetch the data from the API and display it using the ExpansionTile widget. Here is an example:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late Future<List<MyData>> _data;
@override
void initState() {
super.initState();
_data = fetchData();
}
Future<List<MyData>> fetchData() async {
final response = await http.get(Uri.parse('https://example.com/api/data'));
if (response.statusCode == 200) {
final List<dynamic> jsonData = jsonDecode(response.body);
return jsonData.map((item) => MyData.fromJson(item)).toList();
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<MyData>>(
future: _data,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final data = snapshot.data![index];
return ExpansionTile(
title: Text(data.title),
children: data.items.map((item) => ListTile(title: Text(item))).toList(),
);
},
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Center(child: CircularProgressIndicator());
}
},
);
}
}
Replace
'https://example.com/api/data'
with the actual URL of your JSON API endpoint.Use the
MyWidget
in your app'sbuild
method or wherever you want to display the data:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('My App')),
body: MyWidget(),
),
);
}
}
That's it! The ExpansionTile
widgets will display the data from the JSON API in an expandable format.