Networking and making HTTP requests are crucial aspects of building mobile applications, including those developed using Flutter. In this tutorial, we'll explore how to perform networking tasks and make HTTP requests in a Flutter app, including fetching data from an API and handling responses.
1.Using the 'http' Package
Flutter provides the 'http' package to make HTTP requests to remote servers. You need to add this package to your 'pubspec.yaml' file to use it.
Step 1: Add the 'http' Package
In your 'pubspec.yaml' file, add the 'http' package to your dependencies:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3 # Use the latest version
Run 'flutter pub get' to fetch the package.
Step 2: Import the 'http' Package
In your Dart code, import the 'http' package:
import 'package:http/http.dart' as http;
2.Making GET Requests
Let's start by making a simple GET request to fetch data from a public API. In this example, we'll use the JSONPlaceholder API, which provides placeholder data.
Example: Making a GET Request
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Networking and HTTP Requests Tutorial',
home: HttpRequestExample(),
);
}
}
class HttpRequestExample extends StatefulWidget {
@override
_HttpRequestExampleState createState() => _HttpRequestExampleState();
}
class _HttpRequestExampleState extends State {
Future>> 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 data = json.decode(response.body);
return data.cast
In this code, we define an asynchronous function 'fetchData' that makes a GET request to the JSONPlaceholder API and fetches a list of posts. We use 'http.get' to send the request and handle the response using a 'FutureBuilder'. If the response is successful (status code 200), we parse the JSON data and display it in a 'ListView'.
3. Making POST Requests
To make a POST request with the 'http' package, you can use the 'http.post' method. In this example, we'll send a POST request to the JSONPlaceholder API to create a new post.
Example: Making a POST Request
Future createPost() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
{
'title': 'New Post',
'body': 'This is the body of the new post.',
'userId': 1,
},
),
);
if (response.statusCode == 201) {
// If the server returns a 201 Created response,
// the post was successfully created.
print('Post created');
} else {
// If the server did not return a 201 Created response,
// throw an exception.
throw Exception('Failed to create post');
}
}
In this code, we use 'http.post' to send a POST request to the API with the appropriate headers and a JSON-encoded request body. We check the status code in the response to confirm whether the request was successful.
Conclusion:
Performing networking and making HTTP requests is essential for interacting with remote data sources and APIs in Flutter applications. By using the 'http' package, you can easily fetch and send data over the network. Be sure to handle different HTTP status codes and error scenarios appropriately in your Flutter app to ensure a robust and reliable user experience.