Flutter – Sending Data To The Internet

Interacting with the Internet is crucial for most apps to function. In Flutter the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. To send data to the internet through your application follow the below steps:

  1. Import the http package
  2. Send data to the server through the http package
  3. Change the response into custom dart object
  4. Display the response

Importing The http Package:

To install the http package use the below command in your command prompt:

pub get

or, if you are using the flutter cmd use the below command:

flutter pub get

dependencies

After the installation add the dependency to the pubsec.yml file as shown below:



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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map

chevron_right


Convert http.Respone 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Ask User For an Album Title:

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

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: _controller,
        decoration: InputDecoration(hintText: 'Enter Title'),
      ),
    ),
    RaisedButton(
      child: Text('Create Data'),
      onPressed: () {
        setState(() {
          _futureAlbum = createAlbum(_controller.text);
        });
      },
    ),
  ],
)

chevron_right


Display the Response:

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

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

FutureBuilder<Album>(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
  
    return CircularProgressIndicator();
  },
)

chevron_right


Complete Source Code:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

import 'dart:async';
import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
Future<Album> createAlbum(String title) async {
  final http.Response response = await http.post(
    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({this.id, this.title});
  
  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _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',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          child: (_futureAlbum == null)
              ? Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                controller: _controller,
                decoration: InputDecoration(hintText: 'Enter Title'),
              ),
              RaisedButton(
                child: Text('Create Data'),
                onPressed: () {
                  setState(() {
                    _futureAlbum = createAlbum(_controller.text);
                  });
                },
              ),
            ],
          )
              : FutureBuilder<Album>(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
  
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

chevron_right


Output:




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.