Flutter - Updating Data on the Internet - GeeksforGeeks

14 Aug, 2021
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.
To update the data on the Internet follow the below steps:
Import the http packageUpdate data t using the http packageConvert the response into custom Dart objectGet the data from the internet.Update and display the response on screen
Import the http package
Update data t using the http package
Convert the response into custom Dart object
Get the data from the internet.
Update and display the response on screen
To install the http package use the below command in your command prompt:
pub get
Or, if you’re using the flutter cmd use the below command:
flutter pub get
After the installation add the dependency to the pubsec.yml file as shown below:
import 'package:http/http.dart' as http;
Use the http.put() method to update the title of the Album in JSONPlaceholder as shown below:
Dart
Future<http.Response> updateAlbum(String title) {  return http.put(    'https://jsonplaceholder.typicode.com/albums/1',    headers: <String, String>{      'Content-Type': 'application/json; charset=UTF-8',    },    body: jsonEncode(<String, String>{      'title': title,    }),  );}
Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, converting 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({this.id, this.title});   factory Album.fromJson(Map<String, dynamic> json) {    return Album(      id: json['id'],      title: json['title'],    );  }}
Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:
Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200.
Use the dart: convert package to convert the response body into a JSON Map.
Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.
Throw an exception if the server doesn’t return an OK response with a status code of 200.
Dart
Future<Album> updateAlbum(String title) async {  final http.Response response = await http.put(    '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 == 200) {    return Album.fromJson(json.decode(response.body));  } else {    throw Exception('Failed to load album');  }}
Now use the fetch() method to fetch the data as shown below:
Dart
Future<Album> fetchAlbum() async {  final response =      await http.get('https://jsonplaceholder.typicode.com/albums/1');   if (response.statusCode == 200) {    return Album.fromJson(json.decode(response.body));  } else {    throw Exception('Failed to load album');  }}
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>[    Padding(      padding: const EdgeInsets.all(8.0),      child: TextField(        controller: _controller,        decoration: InputDecoration(hintText: 'Enter Title'),      ),    ),    RaisedButton(      child: Text('Update Data'),      onPressed: () {        setState(() {          _futureAlbum = updateAlbum(_controller.text);        });      },    ),  ],)
Use the FlutterBuilder widget to display the data on the screen as shown below:
Dart
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();  },)
Complete Source Code:
Dart
import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async {  final response =  await http.get('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<Album> updateAlbum(String title) async {  final http.Response response = await http.put(    '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({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  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: Text('GeeksForGeeks'),          backgroundColor: Colors.green,        ),        body: Container(          alignment: Alignment.center,          padding: const EdgeInsets.all(8.0),          child: FutureBuilder<Album>(            future: _futureAlbum,            builder: (context, snapshot) {              if (snapshot.connectionState == ConnectionState.done) {                if (snapshot.hasData) {                  return Column(                    mainAxisAlignment: MainAxisAlignment.center,                    children: <Widget>[                      Text(snapshot.data.title),                      TextField(                        controller: _controller,                        decoration: InputDecoration(hintText: 'Enter Title'),                      ),                      RaisedButton(                        child: Text('Update Data'),                        onPressed: () {                          setState(() {                            _futureAlbum = updateAlbum(_controller.text);                          });                        },                      ),                    ],                  );                } else if (snapshot.hasError) {                  return Text("${snapshot.error}");                }              }              return CircularProgressIndicator();            },          ),        ),      ),    );  }}
Output:
sumitgumber28
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
Flutter - Flexible Widget