0% found this document useful (0 votes)
7 views

API Basics and Data Fetching in Flutter

This document provides an overview of using APIs in Flutter, detailing how to make HTTP requests to fetch and send data. It covers the basics of APIs, including GET and POST requests, parsing JSON data, and displaying the fetched data in a Flutter app. The guide emphasizes the importance of APIs in modern app development and provides code examples for practical implementation.

Uploaded by

Zahraa A Genedy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

API Basics and Data Fetching in Flutter

This document provides an overview of using APIs in Flutter, detailing how to make HTTP requests to fetch and send data. It covers the basics of APIs, including GET and POST requests, parsing JSON data, and displaying the fetched data in a Flutter app. The guide emphasizes the importance of APIs in modern app development and provides code examples for practical implementation.

Uploaded by

Zahraa A Genedy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

API Basics and Data Fetching in Flutter

Introduction
In modern app development, APIs (Application Programming Interfaces) play a crucial role in enabling
communication between applications and external services. APIs allow your app to request data from
servers, interact with third-party services, or send data to be processed. In Flutter, consuming an API
typically involves making HTTP requests, handling the response, and displaying the data in your app.
This guide will cover the basics of APIs, how to make API calls in Flutter, and how to display the data
you fetch from the server.
What is an API?
An API (Application Programming Interface) is a set of rules that allows one software application to
interact with another. It specifies how requests and responses are formatted and how the data is
exchanged. APIs allow developers to access functionalities or data from other applications or services
without needing to understand their internal workings.
Common examples of APIs are:
• REST APIs: These APIs use HTTP requests to get, put, post, and delete data.
• GraphQL: An alternative to REST, GraphQL allows clients to request specific data.
• SOAP APIs: An older protocol used for exchanging structured information in a decentralized,
distributed environment.
How APIs Work
An API typically follows a client-server model:
• Client: The app or device making the request for data (your Flutter app).
• Server: The service that processes the request and sends back a response (e.g., a database
server or external service).
The communication between the client and server usually happens over the HTTP(S) protocol, where
the client sends an HTTP request and the server responds with data.
Making API Calls in Flutter
In Flutter, you can use the http package to make HTTP requests. This package allows you to interact
with REST APIs and get data in JSON format.
1. Add Dependencies
To use the http package, you need to add it to your pubspec.yaml file:
yaml
‫نسختحرير‬
dependencies:
http: ^0.13.4 # Check for the latest version
Run the following command to install the package:
bash
‫نسختحرير‬
flutter pub get
2. Import the HTTP Package
Import the http package into the Dart file where you will make the API requests:
dart
‫نسختحرير‬
import 'package:http/http.dart' as http;
import 'dart:convert';
3. Making a GET Request
The most common type of HTTP request is the GET request, which retrieves data from a server. Here's
an example of how to make a simple GET request:
dart
‫نسختحرير‬
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

if (response.statusCode == 200) {
// If the server returns a 200 OK response, parse the JSON
List<dynamic> data = json.decode(response.body);
print(data);
} else {
// If the server did not return a 200 OK response, throw an exception
throw Exception('Failed to load data');
}
}
4. Making a POST Request
Sometimes you might need to send data to the server. A POST request is used to send data. Here’s how
you can make a POST request in Flutter:
dart
‫نسختحرير‬
Future<void> postData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'title': 'foo',
'body': 'bar',
'userId': 1,
}),
);

if (response.statusCode == 201) {
// If the server returns a 201 Created response, handle the success
print('Data posted successfully');
} else {
// If the server did not return a 201 Created response, throw an exception
throw Exception('Failed to post data');
}
}
5. Parsing JSON Data
API responses are often in JSON format, which is easy to parse into Dart objects. You can use
json.decode() to convert the JSON string into a Dart object (like a List or Map).
Here’s an example of parsing the JSON response into a list of posts:
dart
‫نسختحرير‬
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}
Where Post is a model class you define for the data:
dart
‫نسختحرير‬
class Post {
final int id;
final String title;
final String body;

Post({required this.id, required this.title, required this.body});

factory Post.fromJson(Map<String, dynamic> json) {


return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
Displaying Data in Flutter UI
Once the data is fetched from the API, you can display it in your Flutter app. You can use Flutter’s
widget system to display the list of posts.
Here’s an example of displaying a list of posts fetched from an API:
dart
‫نسختحرير‬
class PostListScreen extends StatefulWidget {
@override
_PostListScreenState createState() => _PostListScreenState();
}

class _PostListScreenState extends State<PostListScreen> {


late Future<List<Post>> futurePosts;

@override
void initState() {
super.initState();
futurePosts = fetchPosts();
}

Future<List<Post>> fetchPosts() async {


final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

if (response.statusCode == 200) {
return parsePosts(response.body);
} else {
throw Exception('Failed to load posts');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Posts')),
body: FutureBuilder<List<Post>>(
future: futurePosts,
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 Center(child: Text('No data available'));
} else {
final posts = snapshot.data!;
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(posts[index].title),
subtitle: Text(posts[index].body),
);
},
);
}
},
),
);
}
}
Conclusion
APIs are an essential part of modern mobile apps, and Flutter makes it easy to work with APIs using the
http package. With GET and POST requests, you can fetch and send data to and from a server. You can
then parse the JSON data and display it in your app’s UI. Whether you are fetching user data, posting
content, or integrating third-party services, knowing how to work with APIs is crucial for building
dynamic and responsive apps.

You might also like