API Calls in Flutter
Flutter is a powerful framework for building cross-platform mobile applications. A crucial aspect of any modern app is its ability to fetch and send data over the internet. In this blog, we will explore different ways to make API calls in Flutter.
1. Using http Package
The http package is the most common way to make API calls in Flutter. It provides simple methods to send GET, POST, PUT, and DELETE requests.
Installation:
Add the following dependency in your pubspec.yaml file:
dependencies:
http: ^0.13.4
Run flutter pub get to install the package.
Example:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
final response = await http.get(Uri.parse(''))
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
} else {
throw Exception('Failed to load data');
}
}
2. Using Dio Package
Dio is a powerful HTTP client for Dart, offering advanced features like interceptors, global configuration, and response handling.
Installation:
dependencies:
dio: ^5.0.0
Example:
import 'package:dio/dio.dart';
Future<void> fetchData() async {
var dio = Dio();
try {
final response = await dio.get('');
print(response.data);
} catch (e) {
print('Error: $e');
}
}
3. Using Retrofit
Retrofit is a type-safe HTTP client built on Dio. It simplifies API handling using annotations.
Installation:
dependencies:
retrofit: ^4.0.1
dio: ^5.0.0
json_annotation: ^4.4.0
dev_dependencies:
retrofit_generator: ^4.0.1
build_runner: ^2.1.7
Example:
Create an API client using annotations:
import 'package:dio/dio.dart';
import 'package:retrofit/http.dart';
part 'api_service.g.dart';
@RestApi(baseUrl: "")
abstract class ApiService {
factory ApiService(Dio dio, {String baseUrl}) = _ApiService;
@GET("/posts/1")
Future<Map<String, dynamic>> getPost();
}
Run flutter pub run build_runner build to generate necessary files.
final HttpLink httpLink = HttpLink('https://example.com/graphql');
Future<void> fetchGraphQLData() async {
final GraphQLClient client = GraphQLClient(
link: httpLink,
cache: GraphQLCache(),
);
const String query = '''
query GetPost {
post(id: 1) {
title
body
}
]
Conclusion
Flutter provides multiple ways to make API calls, depending on the complexity and needs of your application.
- Use http for simple API requests.
- Use Dio for advanced networking features.
- Use Retrofit for structured API calls.
Choose the best approach based on your project's requirements. Happy coding! 🚀