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

Don't miss ourDecember livestream, with updates on Flutter and live Q&A!

Fetch data from the internet

How to fetch data over the internet using the http package.

Fetching data from the internet is necessary for most apps. Luckily, Dart and Flutter provide tools, such as thehttp package, for this type of work.

Note

You should avoid directly usingdart:io ordart:html to make HTTP requests. Those libraries are platform-dependent and tied to a single implementation.

This recipe uses the following steps:

  1. Add thehttp package.
  2. Make a network request using thehttp package.
  3. Convert the response into a custom Dart object.
  4. Fetch and display the data with Flutter.

Thehttp package provides the simplest way to fetch data from the internet.

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

flutter pub add http

Import the http 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. Make a network request

#

This recipe covers how to fetch a sample album from theJSONPlaceholder using thehttp.get() method.

dart
Future<http.Response>fetchAlbum(){returnhttp.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));}

Thehttp.get() method returns aFuture that contains aResponse.

  • Future is a core Dart class for working with async operations. A Future 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.

3. Convert the response into 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 anAlbum 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 usingpattern matching is only one option. For more information, see the full article onJSON and serialization.

dart
classAlbum{finalintuserId;finalintid;finalStringtitle;constAlbum({requiredthis.userId,requiredthis.id,requiredthis.title});factoryAlbum.fromJson(Map<String,dynamic>json){returnswitch(json){{'userId':intuserId,'id':intid,'title':Stringtitle}=>Album(userId:userId,id:id,title:title,),_=>throwconstFormatException('Failed to load album.'),};}}

Convert thehttp.Response to anAlbum

#

Now, use the following steps to update thefetchAlbum() function to return aFuture<Album>:

  1. Convert the response body into a JSONMap with thedart:convert package.
  2. If the server does return an OK response with a status code of 200, then convert the JSONMap into anAlbum using thefromJson() factory method.
  3. If the server does not return an OK 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>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');}}

Hooray! Now you've got a function that fetches an album from the internet.

4. Fetch the data

#

Call thefetchAlbum() method in either theinitState() ordidChangeDependencies() methods.

TheinitState() method is called exactly once and then never again. If you want to have the option of reloading the API in response to anInheritedWidget changing, put the call into thedidChangeDependencies() method. SeeState for more details.

dart
class_MyAppStateextendsState<MyApp>{lateFuture<Album>futureAlbum;@overridevoidinitState(){super.initState();futureAlbum=fetchAlbum();}// ···}

This Future is used in the next step.

5. Display the data

#

To display the data on screen, use theFutureBuilder widget. TheFutureBuilder widget comes with Flutter and makes it easy to work with asynchronous data sources.

You must provide two parameters:

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

BecausefetchAlbum can only return non-null values, the function should throw an exception even in the case of a "404 Not Found" server response. Throwing an exception sets thesnapshot.hasError totrue which can be used to display an error message.

Otherwise, the spinner will be displayed.

dart
FutureBuilder<Album>(future:futureAlbum,builder:(context,snapshot){if(snapshot.hasData){returnText(snapshot.data!.title);}elseif(snapshot.hasError){returnText('${snapshot.error}');}// By default, show a loading spinner.returnconstCircularProgressIndicator();},)

Why is fetchAlbum() called in initState()?

#

Although it's convenient, it's not recommended to put an API call in abuild() method.

Flutter calls thebuild() method every time it needs to change anything in the view, and this happens surprisingly often. ThefetchAlbum() method, if placed insidebuild(), is repeatedly called on each rebuild causing the app to slow down.

Storing thefetchAlbum() result in a state variable ensures that theFuture is executed only once and then cached for subsequent rebuilds.

Testing

#

For information on how to test this functionality, see the following recipes:

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');}}classAlbum{finalintuserId;finalintid;finalStringtitle;constAlbum({requiredthis.userId,requiredthis.id,requiredthis.title});factoryAlbum.fromJson(Map<String,dynamic>json){returnswitch(json){{'userId':intuserId,'id':intid,'title':Stringtitle}=>Album(userId:userId,id:id,title:title,),_=>throwconstFormatException('Failed to load album.'),};}}voidmain()=>runApp(constMyApp());classMyAppextendsStatefulWidget{constMyApp({super.key});@overrideState<MyApp>createState()=>_MyAppState();}class_MyAppStateextendsState<MyApp>{lateFuture<Album>futureAlbum;@overridevoidinitState(){super.initState();futureAlbum=fetchAlbum();}@overrideWidgetbuild(BuildContextcontext){returnMaterialApp(title:'Fetch Data Example',theme:ThemeData(colorScheme:ColorScheme.fromSeed(seedColor:Colors.deepPurple),),home:Scaffold(appBar:AppBar(title:constText('Fetch Data Example')),body:Center(child:FutureBuilder<Album>(future:futureAlbum,builder:(context,snapshot){if(snapshot.hasData){returnText(snapshot.data!.title);}elseif(snapshot.hasError){returnText('${snapshot.error}');}// By default, show a loading spinner.returnconstCircularProgressIndicator();},),),),);}}
Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Flutter 3.38.1. Page last updated on 2025-10-28.View source orreport an issue.


[8]ページ先頭

©2009-2025 Movatter.jp