Learn how to make HTTP requests in Flutter to fetch data from APIs, using the http package for GET requests.
In this section, we will embark on an exciting journey to learn how to fetch data from the internet using Flutter. Imagine being able to ask a website for information and getting it back to use in your app—this is what making requests is all about!
Making a request is like asking a friend for a piece of information. When you make a request to a website or an online service, you’re asking it to send you some data. This data could be anything from the latest news articles to a random joke. In the world of coding, these requests are often made to something called an API (Application Programming Interface).
There are several types of HTTP requests, but the most common one for fetching data is the GET request. Think of a GET request as a polite way of saying, “Please give me this information.” It’s the type of request we’ll focus on in this section.
To make requests in Flutter, we use a special tool called the http
package. This package helps us send requests and handle the responses we get back.
http
PackageFirst, we need to add the http
package to our Flutter project. This package allows us to make HTTP requests easily.
Open your pubspec.yaml
file and add the following line under dependencies:
dependencies:
http: ^0.13.5
After adding this line, save the file and run flutter pub get
in your terminal to install the package.
Let’s write a simple function to make a GET request and fetch some data. We’ll use a fictional API for this example.
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
} else {
print('Failed to load data');
}
}
Import Statements: We start by importing the http
package and dart:convert
. The http
package helps us make requests, while dart:convert
allows us to work with JSON data.
Making the Request: The http.get
function sends a GET request to the URL we provide. In this case, it’s 'https://api.example.com/data'
.
Handling the Response: After sending the request, we check if the response was successful by looking at the statusCode
. A status code of 200 means success. We then decode the JSON response using jsonDecode
and print the data.
To better understand how making a request works, let’s look at a flowchart:
graph TD A[App] --> B[Send GET Request] B --> C[API Server] C --> D[Return Data] D --> E[App Processes Data]
This flowchart shows the journey of a request from your app to the API server and back. Your app sends a request, the server processes it, and then sends the data back to your app.
Imagine you’re building a “News Reader” app. You can use what you’ve learned to fetch the latest news articles from a news API. This way, your app can always display the most current news to its users.
Now it’s your turn! Try writing a function that makes a GET request to a public API, like fetching a random joke. Here’s a hint to get you started:
Future<void> fetchJoke() async {
final response = await http.get(Uri.parse('https://official-joke-api.appspot.com/random_joke'));
if (response.statusCode == 200) {
var joke = jsonDecode(response.body);
print('Here\'s a joke: ${joke['setup']} - ${joke['punchline']}');
} else {
print('Failed to load joke');
}
}
Annotated code snippets and flowcharts are great tools to help visualize the request process. Use them to understand each step and see how data flows from the API to your app.