Send data to the internet

Sending data to the internet is necessary for most apps. The http package has got that covered, too.

This recipe uses the following steps:

  1. Add the http package.
  2. Send data to a server using the http package.
  3. Convert the response into a custom Dart object.
  4. Get a title from user input.
  5. Display the response on screen.

1. Add the http package

To add the http package as a dependency, run flutter pub add:

flutter pub add http

Import the http package.

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

If you are deploying to Android, edit your AndroidManifest.xml file to add the Internet permission.

<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

Likewise, if you are deploying to macOS, edit your macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements files to include the network client entitlement.

<!-- Required to fetch data from the internet. -->
<key>com.apple.security.network.client</key>
<true/>

2. Sending data to server

This recipe covers how to create an Album by sending an album title to the JSONPlaceholder using the http.post() method.

Import dart:convert for access to jsonEncode to encode the data:

import 'dart:convert';

Use the http.post() method to send the encoded data:

Future<http.Response> createAlbum(String title) {
  return http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{'title': title}),
  );
}