Open In App

Flutter - Sending Data To The Internet

Last Updated : 07 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Interacting with the Internet is crucial for most apps to function. In Flutter, sending data to the internet is one of them, and the http package is used to send the data to the internet. In this article, we will explore the same topic in detail.

Steps to Implement Sending Data to the Internet

Step 1: Create a new flutter application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add http as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
      flutter:
        sdk: flutter
      http: ^1.3.0

Now run the below command in the terminal.

flutter pub get

Step 3: Importing the Dependency

Use the below line of code in the main.dart file, to import the shimmer dependency :

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

Step 4: Follow below flow to send data to the internet

- Send Data to the Server

In this article, we will create an Album data and send it to JSONPlaceholder through the http.post() method.

Dart
Future<Album> createAlbum(String title) async {
  final http.Response response = await 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,
        }),
  );


- Converting the Response

Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, convert the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below:

Dart
class Album {
  final int id;
  final String title;

  Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}


- Convert http.Response to an Album

Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:

  1. Use the dart: convert package to convert the response body into a JSON Map.
  2. Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.
  3. Throw an exception if the server doesn't return an OK response with a status code of 200.
Dart
import 'dart:convert';
Future<Album> createAlbum(String title) async {
  final http.Response response = await http.post(
        'https://jsonplaceholder.typicode.com/albums',
        headers: <String, String>{
             'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
              'title': title,
        }),
  );
  // Dispatch action depending upon 
  // the server response
  if (response.statusCode == 201) {
         return Album.fromJson(json.decode(response.body));
  } else {
         throw Exception('Album loading failed!');
  }
}


- Ask User For an Album Title

Now create a TextField  for the user to enter a title and a ElevatedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below:

Dart
final TextEditingController _controller = TextEditingController();
......

Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
            TextField(
                  controller: _controller,
                  decoration:
                      const InputDecoration(hintText: 'Enter Title'),
            ),
            SizedBox(
                 height: 10,
            ),
            ElevatedButton(
                  style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green,
                          foregroundColor: Colors.white
                      ),
                  child: const Text('Create Data'),
                  onPressed: () {
                        setState(() {
                          _futureAlbum = createAlbum(_controller.text);
                        });
                  },
            ),
      ],
)

To know more about ElevatedButton in flutter refer this article: Flutter – ElevatedButton Widget

- Display the Response

Use the FlutterBuilder widget to display the data on the screen as shown below:

Dart
Future<Album>? _futureAlbum;
.......

FutureBuilder<Album>(
      future: _futureAlbum,
      builder: (context, snapshot) {
            if (snapshot.hasData) {
                 return Text(
                        snapshot.data!.title,
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
              );
            } else if (snapshot.hasError) {
                 return Text("${snapshot.error}");
            }
        
            return const CircularProgressIndicator();
      },
),


Complete Source Code

main.dart:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
// ignore: library_private_types_in_public_api
  _MyAppState createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  Future<Album>? _futureAlbum;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Creating Data',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
          foregroundColor: Colors.white,
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          // ignore: unnecessary_null_comparison
          child: (_futureAlbum == null)
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    TextField(
                      controller: _controller,
                      decoration:
                          const InputDecoration(hintText: 'Enter Title'),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green,
                          foregroundColor: Colors.white),
                      child: const Text('Create Data'),
                      onPressed: () {
                        setState(() {
                          _futureAlbum = createAlbum(_controller.text);
                        });
                      },
                    ),
                  ],
                )
              : FutureBuilder<Album>(
                  future: _futureAlbum,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return Text(
                        snapshot.data!.title,
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
                      );
                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}");
                    }

                    return const CircularProgressIndicator();
                  },
                ),
        ),
      ),
    );
  }
}

Future<Album> createAlbum(String title) async {
  final http.Response response = await 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,
    }),
  );

  if (response.statusCode == 201) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}

class Album {
  final int id;
  final String title;

  Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}


Output:



Next Article
Article Tags :

Similar Reads