How to Fetch and Display API Data in Flutter: A Step-by-Step Guide
Introduction
Fetching data from an API and displaying it in a mobile app is a common requirement for many applications. In this tutorial, we will walk you through the steps to fetch data from an API and display it in a Flutter application. We will use a simple example to demonstrate how to make an HTTP GET request, parse the JSON response, and display the data in a list.
Prerequisites
Before we start, ensure you have the following:
- Flutter installed on your machine
- Basic knowledge of Dart programming
- A code editor like VSCode or Android Studio
Step 1: Setting Up Your Flutter Project
First, create a new Flutter project using the following command:
Navigate to the project directory:
Open the pubspec.yaml
file and add the http
dependency:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
Run flutter pub get
to install the new dependency.
Step 2: Creating Data Models
We need to create Dart classes to model the API response. These classes will help us parse the JSON data returned by the API.
Create a new file named models.dart
in the lib
directory and add the following code:
class Pagination {
final int totalItems;
final int perPage;
final int currentPage;
final int totalPages;
final int from;
final int to;
final dynamic nextPage;
final dynamic previousPage;
Pagination({
required this.totalItems,
required this.perPage,
required this.currentPage,
required this.totalPages,
required this.from,
required this.to,
this.nextPage,
this.previousPage,
});
factory Pagination.fromJson(Map<String, dynamic> json) {
return Pagination(
totalItems: json['total_items'],
perPage: json['per_page'],
currentPage: json['currentPage'],
totalPages: json['totalPages'],
from: json['from'],
to: json['to'],
nextPage: json['next_page'],
previousPage: json['previous_page'],
);
}
}
class DataItem {
final int id;
final String name;
final int commission;
final int status;
final String type;
final String createdAt;
final String? updatedAt;
final String? deletedAt;
DataItem({
required this.id,
required this.name,
required this.commission,
required this.status,
required this.type,
required this.createdAt,
this.updatedAt,
this.deletedAt,
});
factory DataItem.fromJson(Map<String, dynamic> json) {
return DataItem(
id: json['id'],
name: json['name'],
commission: json['commission'],
status: json['status'],
type: json['type'],
createdAt: json['created_at'],
updatedAt: json['updated_at'],
deletedAt: json['deleted_at'],
);
}
}
class ApiResponse {
final Pagination pagination;
final List<DataItem> data;
ApiResponse({required this.pagination, required this.data});
factory ApiResponse.fromJson(Map<String, dynamic> json) {
return ApiResponse(
pagination: Pagination.fromJson(json['pagination']),
data: (json['data'] as List)
.map((dataItem) => DataItem.fromJson(dataItem))
.toList(),
);
}
}
Step 3: Fetching Data from the API
Next, we will create a function to make an HTTP GET request to fetch data from the API.
Update your main.dart
file as follows:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({super.key});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late Future<ApiResponse> futureApiResponse;
@override
void initState() {
super.initState();
futureApiResponse = fetchApiResponse();
}
Future<ApiResponse> fetchApiResponse() async {
final url = "http://urbanflowservice.hirenow.co.in/api/type-list";
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return ApiResponse.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load data');
}
} catch (error) {
rethrow;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Data'),
),
body: FutureBuilder<ApiResponse>(
future: futureApiResponse,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.data.length,
itemBuilder: (context, index) {
final item = snapshot.data!.data[index];
return ListTile(
title: Text(item.name),
subtitle: Text('Commission: ${item.createdAt}'),
);
},
);
} else {
return Center(child: Text('No data found'));
}
},
),
);
}
}
Conclusion
In this tutorial, we demonstrated how to fetch data from an API and display it in a Flutter app. We covered setting up the Flutter project, creating data models, making an HTTP GET request, and displaying the data in the UI using a FutureBuilder
. This basic example can be extended and customized to suit your application's requirements. Experiment with different APIs and explore the possibilities of integrating external data sources into your Flutter apps. Happy coding!
Comments
Post a Comment