How to Send Data On Flutter

Every now and then your app needs to not only read data on the internet but send data through the internet as well. That is why in today’s post we are going to discuss how to send data through the internet on Flutter.


Prerequisites

Firstly, we need a package to communicate through the internet, and that’s where the HTTP packages come in handy. Make sure to add it to your Flutter project. You can also check out this blog on how to do it. Also don’t forget to import it.

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

Additionally, you need to allow your app project to access the internet by changing the Android manifest file to the code below.

<uses-permission android:name="android.permission.INTERNET"/>

Sending Data Using HTTP On Flutter

This blog describes how to build an album by utilizing the http.post() function to submit an album title to the JSONPlaceholder. The http.post() method returns a Future containing a Response. A Future object represents a possible value or error that will become available in the future. The createAlbum() method accepts an argument title and sends it to the server in order to make an album. All of which are necessary for us to send data on Flutter.

To that end, we can now make the Album class and covert that JSON response into a dart object. Let’s get started!

First, create an Album class to hold the data from the network request. It contains a factory constructor for generating an Album from JSON.

class Album {
  final int id;
  final String title;

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

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

Now, let’s convert that JSON response into the Album class. Using the code below, take note that if the server doesn’t return a CREATED response with a status code of 201, then throw an exception. Do not return null. This is important when examining the data in snapshot form. Use the dart:convert package to convert the response body into a JSON Map.

Future<Album> createAlbum(String title) async {
  final 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(jsonDecode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}

You can finally use the code now that you have most of the tedious parts of it. You can check the full code below, or you can check the official docs for more information.

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 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) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}

class Album {
  final int id;
  final String title;

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

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

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Create Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Create Data Example'),
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          child: (_futureAlbum == null) ? buildColumn() : buildFutureBuilder(),
        ),
      ),
    );
  }

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

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

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

Conclusion

To conclude, we now know how to send data through the internet on Flutter. Then we created an Album class to hold the data from the network request. Then finally, use Dart to convert the response body into a JSON Map. Thank you for reading, If you found this useful please share it with your family and friends. Farewell!

Leave a Comment

Your email address will not be published. Required fields are marked *