Flutter Updating Data on the Internet (original) (raw)

Last Updated : 03 May, 2025

In today's world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same. Let's see a sample video of what we are going to develop.

**Sample Video:

Step-by-Step Implementation

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following 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 command below in the terminal.

flutter pub get

**Or

Run the command below in the terminal.

flutter pub add http

Step 3: Import dependencies

To use libraries, import all of them in the respective .dart file.

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

Step 4: Start Coding

**- **Update Data over the Internet

Use the **http.put() method to update the title of the Album in JSONPlaceholder as shown below:

Dart `

Future updateAlbum(String title) async { final http.Response response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), 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 a 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 steps below to update the _fetchAlbum() function to return a Future:

  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 `

Future updateAlbum(String title) async { final http.Response response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // parsing JSOn or throwing an exception if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); } }

`

- **Fetching the Data

Now use the fetch() method to fetch the data as shown below:

Dart `

Future fetchAlbum() async { final response = await http .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

// Dispatch action depending upon //the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); } }

`

- **Update the existing Data through user input

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 `

            Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(snapshot.data!.title),
                  TextField(
                    controller: _controller,
                    decoration:
                        const InputDecoration(hintText: 'Enter Title'),
                  ),
                  
                  ElevatedButton(
                    child: const Text('Update Data'),
                    onPressed: () {
                      setState(() {
                        _futureAlbum = updateAlbum(_controller.text);
                      });
                    },
                  )

`

**- **Displaying the Data

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

Dart `

FutureBuilder( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(snapshot.data!.title), TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ) ], ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } } return const CircularProgressIndicator(); }, ),

`

**Complete Source Code:

Dart `

import 'dart:async'; import 'dart:convert';

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

Future fetchAlbum() async { final response = await http .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

// Dispatch action depending upon //the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); } }

Future updateAlbum(String title) async { final http.Response response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // parsing JSOn or throwing an exception if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update 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'], ); } }

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 { final TextEditingController _controller = TextEditingController(); late Future _futureAlbum;

@override void initState() { super.initState(); _futureAlbum = fetchAlbum(); }

@override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: FutureBuilder( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(snapshot.data!.title), TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter Title'), ), ElevatedButton( child: const Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, )

                  // RaisedButton is deprecated and should not be used.
                  // Use ElevatedButton instead.

                  // RaisedButton(
                  //     child: const Text('Update Data'),
                  //     onPressed: () {
                  //     setState(() {
                  //         _futureAlbum = updateAlbum(_controller.text);
                  //     });
                  //     },
                  // ),
                ],
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
          }
          return const CircularProgressIndicator();
        },
      ),
    ),
  ),
);

} }

`

**Output: