Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

docs.flutter.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more

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:

  1. Add thehttp package.
  2. Update data over the internet using thehttp package.
  3. Convert the response into a custom Dart object.
  4. Get the data from the internet.
  5. Update the existingtitle from user input.
  6. Update and display the response on screen.

1. Add thehttp package

#

To add thehttp package as a dependency, runflutter pub add:

flutter pub add http

Import thehttp package.

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

If you are deploying to Android, edit yourAndroidManifest.xml file to add the Internet permission.

xml
<!-- 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.

xml
<!-- 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.

dart
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.

  • Future is a core Dart class for working with async operations. AFuture object represents a potential value or error that will be available at some time in the future.
  • Thehttp.Response class contains the data received from a successful http call.
  • TheupdateAlbum() 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.

dart
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>:

  1. Convert the response body into a JSONMap with thedart:convert package.
  2. If the server returns anUPDATED response with a status code of 200, then convert the JSONMap into anAlbum using thefromJson() factory method.
  3. If the server doesn't return anUPDATED response 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.)
dart
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.

dart
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.

dart
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:

  1. TheFuture you want to work with. In this case, the future returned from theupdateAlbum() function.
  2. Abuilder function 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.

dart
FutureBuilder<Album>(future:_futureAlbum,builder:(context,snapshot){if(snapshot.hasData){returnText(snapshot.data!.title);}elseif(snapshot.hasError){returnText('${snapshot.error}');}returnconstCircularProgressIndicator();},);

Complete example

#
dart
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();},),),),);}}
Was this page's content helpful?

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.


[8]ページ先頭

©2009-2026 Movatter.jp