Learning how to make HTTP requests is essential for any Flutter developer. The http
package in Flutter simplifies networking tasks like fetching data from APIs, sending POST requests, and handling responses. This guide is designed for beginners who are new to Flutter and want to understand how to implement API calls using the http
package effectively.
What is the http
package in Flutter?
The http
package allows developers to perform network requests and interact with REST APIs. It supports GET, POST, PUT, DELETE, and more. It’s one of the most downloaded packages on pub.dev , which ensures it’s reliable and well-maintained.
How to Use HTTP in Flutter
Step 1: Add the Dependency
Add this to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
http: ^0.13.6
dependencies:
flutter:
sdk: flutter
http: ^0.13.6
Then run:
flutter pub get
Step 2: Create a Data Model
Post ({ required this . userId , required this . id , required this . title , required this . body }) ;
factory Post. fromJson ( Map < String , dynamic > json ) {
// file: post_model.dart
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({required this.userId, required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
// file: post_model.dart
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({required this.userId, required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
Step 3: Create an HTTP Service
// file: api_service.dart
import '<a href="https://aliendro.id/micro-habit-tracker-open-source-flutter-habit-app/">dart</a>:convert' ;
import 'package:http/http.dart' as http;
import 'post_model.dart' ;
final String baseUrl = 'https://jsonplaceholder.typicode.com' ;
Future < List < Post >> fetchPosts () async {
final response = await http. get ( Uri. parse ( '$baseUrl/posts' )) ;
if ( response. statusCode == 200 ) {
List jsonData = json. decode ( response. body ) ;
return jsonData. map (( post ) => Post. fromJson ( post )) . toList () ;
throw Exception ( 'Failed to load posts' ) ;
// file: api_service.dart
import '<a href="https://aliendro.id/micro-habit-tracker-open-source-flutter-habit-app/">dart</a>:convert';
import 'package:http/http.dart' as http;
import 'post_model.dart';
class ApiService {
final String baseUrl = 'https://jsonplaceholder.typicode.com';
Future<List<Post>> fetchPosts() async {
final response = await http.get(Uri.parse('$baseUrl/posts'));
if (response.statusCode == 200) {
List jsonData = json.decode(response.body);
return jsonData.map((post) => Post.fromJson(post)).toList();
} else {
throw Exception('Failed to load posts');
}
}
}
// file: api_service.dart
import 'dart :convert';
import 'package:http/http.dart' as http;
import 'post_model.dart';
class ApiService {
final String baseUrl = 'https://jsonplaceholder.typicode.com';
Future<List<Post>> fetchPosts() async {
final response = await http.get(Uri.parse('$baseUrl/posts'));
if (response.statusCode == 200) {
List jsonData = json.decode(response.body);
return jsonData.map((post) => Post.fromJson(post)).toList();
} else {
throw Exception('Failed to load posts');
}
}
}
Step 4: Use in Your Flutter App
import 'package:flutter/material.dart' ;
import 'api_service.dart' ;
import 'post_model.dart' ;
class MyApp extends < a href= "https://aliendro.id/create-ui-with-statelesswidget-in-dart/" > StatelessWidget < /a > {
final ApiService apiService = ApiService () ;
Widget build ( BuildContext context ) {
title: 'HTTP Flutter Demo' ,
appBar: AppBar ( title: Text ( 'Posts' )) ,
body: FutureBuilder < List < Post >>(
future: apiService. fetchPosts () ,
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 found' )) ;
final posts = snapshot. data !;
itemBuilder: ( context, index ) {
title: Text ( posts [ index ] . title ) ,
subtitle: Text ( posts [ index ] . body ) ,
// file: main.dart
import 'package:flutter/material.dart';
import 'api_service.dart';
import 'post_model.dart';
void main() {
runApp(MyApp());
}
class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> {
final ApiService apiService = ApiService();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HTTP Flutter Demo',
home: Scaffold(
appBar: AppBar(title: Text('Posts')),
body: FutureBuilder<List<Post>>(
future: apiService.fetchPosts(),
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 found'));
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),
);
},
);
},
),
),
);
}
}
// file: main.dart
import 'package:flutter/material.dart';
import 'api_service.dart';
import 'post_model.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final ApiService apiService = ApiService();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HTTP Flutter Demo',
home: Scaffold(
appBar: AppBar(title: Text('Posts')),
body: FutureBuilder<List<Post>>(
future: apiService.fetchPosts(),
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 found'));
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
With the http
package in Flutter, making API calls becomes easy and clean. Beginners can fetch and display dynamic data with just a few lines of code. You can also extend this code to support POST or PUT requests as you advance.
Post Views: 29