Using API Requests with HTTP Package in Flutter and Dart

Using API Requests with HTTP Package in Flutter and Dart

The http package in Dart provides high-level functions and classes that allow developers to make HTTP requests to web servers. It provides a simple and convenient way to communicate with APIs and other web services from a Flutter app. It is a future-based library. That means we are going to explore asynchronous operations. It's multi-platform and supports mobile, desktop, and browser.

In this tutorial, we are going to explore, the GET and POST requests. These are the most commonly used HTTP methods.

A GET request is a request made to a server to retrieve data. The client sends a request to the server, asking for a specific resource, and if it's available, the server responds with that data.

POST requests are used to submit data to a server for processing. The client sends data in the body of the request, which is then processed by the server and sent back as a response with any changes made. POST requests are commonly used for form submissions, file uploads and other types of data input.

So let's start!

Install the package

Run the following command to install the package

For Dart

dart pub add http

For flutter

flutter pub add http

In this tutorial, we are going to use the Flutter methods

GET Method

To do a GET API request, we simply call the http.get(url) method and get the result.

import 'package:http/http.dart' as http;

Future<List> fetchTodos() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos'));
  return json.decode(response.body);
}

This method returns a list of todos from https://jsonplaceholder.typicode.com/

This website provides Fake data service for free.

Here is the example that fetches the JSON data from the API using the GET method and displays the first five todos using the ListTIle widget.

main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'http allaboutflutter',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _todos = [];

Future<List> fetchTodos() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos'));
  return json.decode(response.body);
}

  @override
  void initState() {
    super.initState();
    fetchTodos().then((value) {
      setState(() {
        _todos = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('http allaboutflutter'),
      ),
      body: ListView.builder(
        itemCount: _todos.length > 5 ? 5 : _todos.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(_todos[index]['title']),
            subtitle: Text(_todos[index]['completed'] ? 'Completed' : 'Incomplete'),
            leading: CircleAvatar(
              child: Text(_todos[index]['id'].toString()),
            ),
          );
        },
      ),
    );
  }
}
Output

POST Method

Now it is the time to explore the POST method in the http package. Yes it is as simple as calling the http.post(url) method with your headers and data. The exact structure is as follows:

http.post(
  Uri.parse('https://jsonplaceholder.typicode.com/posts'),
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
    // any other headers such as authentication credentials
  },
  body: jsonEncode(<String, dynamic>{}),
);

We will again use JSONPlaceholder to do a POST request and in response we will receive the same data but with an ID.

Here is an example of an http POST request where we are sending dummy data to the API and receiving the response

main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'http allaboutflutter',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _responseText = '';

  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: jsonEncode(<String, dynamic>{
        'title': 'Flutter Post Request Example by allaboutflutter.com using http package',
        'body': 'Learnt a lot from allaboutflutter.com and exploring more',
        'userId': 7
      }),
    );
    setState(() {
      _responseText = response.body;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('POST using http'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            postData();
          },
          child: Text('Make POST Request'),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(_responseText),
        ),
      ),
    );
  }
}

Output

See you in another amazing article. Till then suggest some topics and improvements.

https://pub.dev/packages/http

https://dartpad.dev/?id=c8cb38e3c3ba619d8b5aa90bd66e77f5

Did you find this article valuable?

Support All About Flutter | Flutter and Dart by becoming a sponsor. Any amount is appreciated!