Making HTTP network requests

Domains: Flutter

Fetching data from the internet is common for most apps. And in Flutter, the http package provides the simplest way to fetch data from the internet.

How do I fetch data from API calls?

React Native provides the Fetch API for networking—you make a fetch request and then receive the response to get the data.

// React Native
_getIPAddress = () => {
  fetch('https://httpbin.org/ip')
    .then(response => response.json())
    .then(responseJson => {
      this.setState({ _ipAddress: responseJson.origin });
    })
    .catch(error => {
      console.error(error);
    });
};

Flutter uses the http package. To install the http package, add it to the dependencies section of our pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  http: <latest_version>

Flutter uses the dart:io core HTTP support client. To create an HTTP Client, import dart:io.

import 'dart:io';

The client supports the following HTTP operations: GET, POST, PUT, and DELETE.

// Flutter
final url = Uri.https('httpbin.org', 'ip');
final httpClient = HttpClient();
_getIPAddress() async {
  var request = await httpClient.getUrl(url);
  var response = await request.close();
  var responseBody = await response.transform(utf8.decoder).join();
  String ip = jsonDecode(responseBody)['origin'];
  setState(() {
    _ipAddress = ip;
  });
}

Android

IOS

Similar pages

Page structure
Terms

Flutter