Flutter 3.41 is live! Check out theFlutter 3.41 blog post!
Update data over the internet
How to use the http package to update data over the internet.
Updating data over the internet is necessary for most apps. Thehttp package has got that covered!
This recipe uses the following steps:
- Add the
httppackage. - Update data over the internet using the
httppackage. - Convert the response into a custom Dart object.
- Get the data from the internet.
- Update the existing
titlefrom user input. - Update and display the response on screen.
1. Add thehttp package
# To add thehttp package as a dependency, runflutter pub add:
flutter pub add httpImport thehttp package.
import'package:http/http.dart'ashttp; If you are deploying to Android, edit yourAndroidManifest.xml file to add the Internet permission.
<!-- Required to fetch data from the internet.--><uses-permission android:name="android.permission.INTERNET" /> Likewise, if you are deploying to macOS, edit yourmacos/Runner/DebugProfile.entitlements andmacos/Runner/Release.entitlements files to include the network client entitlement.
<!-- Required to fetch data from the internet.--><key>com.apple.security.network.client</key><true/>2. Updating data over the internet using thehttp package
# This recipe covers how to update an album title to theJSONPlaceholder using thehttp.put() method.
Future<http.Response>updateAlbum(Stringtitle){returnhttp.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}),);} Thehttp.put() method returns aFuture that contains aResponse.
Futureis a core Dart class for working with async operations. AFutureobject represents a potential value or error that will be available at some time in the future.- The
http.Responseclass contains the data received from a successful http call. - The
updateAlbum()method takes an argument,title, which is sent to the server to update theAlbum.
3. Convert thehttp.Response to a custom Dart object
# While it's easy to make a network request, working with a rawFuture<http.Response> isn't very convenient. To make your life easier, convert thehttp.Response into a Dart object.
Create an Album class
# First, create anAlbum class that contains the data from the network request. It includes a factory constructor that creates anAlbum from JSON.
Converting JSON withpattern matching is only one option. For more information, see the full article onJSON and serialization.
classAlbum{finalintid;finalStringtitle;constAlbum({requiredthis.id,requiredthis.title});factoryAlbum.fromJson(Map<String,dynamic>json){returnswitch(json){{'id':intid,'title':Stringtitle}=>Album(id:id,title:title),_=>throwconstFormatException('Failed to load album.'),};}}Convert thehttp.Response to anAlbum
# Now, use the following steps to update theupdateAlbum() function to return aFuture<Album>:
- Convert the response body into a JSON
Mapwith thedart:convertpackage. - If the server returns an
UPDATEDresponse with a status code of 200, then convert the JSONMapinto anAlbumusing thefromJson()factory method. - If the server doesn't return an
UPDATEDresponse with a status code of 200, then throw an exception. (Even in the case of a "404 Not Found" server response, throw an exception. Do not returnnull. This is important when examining the data insnapshot, as shown below.)
Future<Album>updateAlbum(Stringtitle)async{finalresponse=awaithttp.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}),);if(response.statusCode==200){// If the server did return a 200 OK response,// then parse the JSON.returnAlbum.fromJson(jsonDecode(response.body)asMap<String,dynamic>);}else{// If the server did not return a 200 OK response,// then throw an exception.throwException('Failed to update album.');}}Hooray! Now you've got a function that updates the title of an album.
Get the data from the internet
#Get the data from internet before you can update it. For a complete example, see theFetch data recipe.
Future<Album>fetchAlbum()async{finalresponse=awaithttp.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),);if(response.statusCode==200){// If the server did return a 200 OK response,// then parse the JSON.returnAlbum.fromJson(jsonDecode(response.body)asMap<String,dynamic>);}else{// If the server did not return a 200 OK response,// then throw an exception.throwException('Failed to load album');}} Ideally, you will use this method to set_futureAlbum duringinitState to fetch the data from the internet.
4. Update the existing title from user input
# Create aTextField to enter a title and aElevatedButton to update the data on server. Also define aTextEditingController to read the user input from aTextField.
When theElevatedButton is pressed, the_futureAlbum is set to the value returned byupdateAlbum() method.
Column(mainAxisAlignment:MainAxisAlignment.center,children:<Widget>[Padding(padding:constEdgeInsets.all(8),child:TextField(controller:_controller,decoration:constInputDecoration(hintText:'Enter Title'),),),ElevatedButton(onPressed:(){setState((){_futureAlbum=updateAlbum(_controller.text);});},child:constText('Update Data'),),],); On pressing theUpdate Data button, a network request sends the data in theTextField to the server as aPUT request. The_futureAlbum variable is used in the next step.
5. Display the response on screen
# To display the data on screen, use theFutureBuilder widget. TheFutureBuilder widget comes with Flutter and makes it easy to work with async data sources. You must provide two parameters:
- The
Futureyou want to work with. In this case, the future returned from theupdateAlbum()function. - A
builderfunction that tells Flutter what to render, depending on the state of theFuture: loading, success, or error.
Note thatsnapshot.hasData only returnstrue when the snapshot contains a non-null data value. This is why theupdateAlbum function should throw an exception even in the case of a "404 Not Found" server response. IfupdateAlbum returnsnull thenCircularProgressIndicator will display indefinitely.
FutureBuilder<Album>(future:_futureAlbum,builder:(context,snapshot){if(snapshot.hasData){returnText(snapshot.data!.title);}elseif(snapshot.hasError){returnText('${snapshot.error}');}returnconstCircularProgressIndicator();},);Complete example
#import'dart:async';import'dart:convert';import'package:flutter/material.dart';import'package:http/http.dart'ashttp;Future<Album>fetchAlbum()async{finalresponse=awaithttp.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),);if(response.statusCode==200){// If the server did return a 200 OK response,// then parse the JSON.returnAlbum.fromJson(jsonDecode(response.body)asMap<String,dynamic>);}else{// If the server did not return a 200 OK response,// then throw an exception.throwException('Failed to load album');}}Future<Album>updateAlbum(Stringtitle)async{finalresponse=awaithttp.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}),);if(response.statusCode==200){// If the server did return a 200 OK response,// then parse the JSON.returnAlbum.fromJson(jsonDecode(response.body)asMap<String,dynamic>);}else{// If the server did not return a 200 OK response,// then throw an exception.throwException('Failed to update album.');}}classAlbum{finalintid;finalStringtitle;constAlbum({requiredthis.id,requiredthis.title});factoryAlbum.fromJson(Map<String,dynamic>json){returnswitch(json){{'id':intid,'title':Stringtitle}=>Album(id:id,title:title),_=>throwconstFormatException('Failed to load album.'),};}}voidmain(){runApp(constMyApp());}classMyAppextendsStatefulWidget{constMyApp({super.key});@overrideState<MyApp>createState(){return_MyAppState();}}class_MyAppStateextendsState<MyApp>{finalTextEditingController_controller=TextEditingController();lateFuture<Album>_futureAlbum;@overridevoidinitState(){super.initState();_futureAlbum=fetchAlbum();}@overrideWidgetbuild(BuildContextcontext){returnMaterialApp(title:'Update Data Example',theme:ThemeData(colorScheme:ColorScheme.fromSeed(seedColor:Colors.deepPurple),),home:Scaffold(appBar:AppBar(title:constText('Update Data Example')),body:Container(alignment:Alignment.center,padding:constEdgeInsets.all(8),child:FutureBuilder<Album>(future:_futureAlbum,builder:(context,snapshot){if(snapshot.connectionState==ConnectionState.done){if(snapshot.hasData){returnColumn(mainAxisAlignment:MainAxisAlignment.center,children:<Widget>[Text(snapshot.data!.title),TextField(controller:_controller,decoration:constInputDecoration(hintText:'Enter Title',),),ElevatedButton(onPressed:(){setState((){_futureAlbum=updateAlbum(_controller.text);});},child:constText('Update Data'),),],);}elseif(snapshot.hasError){returnText('${snapshot.error}');}}returnconstCircularProgressIndicator();},),),),);}}Unless stated otherwise, the documentation on this site reflects Flutter 3.38.6. Page last updated on 2025-10-28.View source orreport an issue.