Fetching data from the internet is necessary for most apps. Luckily, Dart andFlutter provide tools for this type of work.

Directions

  • Add the http package
  • Make a network request using the http package
  • Convert the response into a custom Dart object
  • Fetch and Display the data with Flutter

1. Add the http package

The http package provides thesimplest way to fetch data from the internet.

To install the http package, you must add it to the dependencies sectionof the pubspec.yaml. You can find the latest version of the http package onthe Pub site.

  1. dependencies:
  2. http: <latest_version>

2. Make a network request

In this example, you’ll fetch a sample post from theJSONPlaceholder REST API using thehttp.get() method.

  1. Future<http.Response> fetchPost() {
  2. return http.get('https://jsonplaceholder.typicode.com/posts/1');
  3. }

The http.get() method returns a Future that contains a Response.

  • Future isa core Dart class for working with async operations.It is used to represent a potential value or error that willbe available at some time in the future.
  • The http.Response class contains the data received from a successfulhttp 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 the http.Response into a Dart object.

Create a Post class

First, create a Post class that contains the data from thenetwork request. It will include a factory constructor that creates a Post from json.

Converting JSON by hand is only one option. For more information,please see the full article on JSON andserialization.

  1. class Post {
  2. final int userId;
  3. final int id;
  4. final String title;
  5. final String body;
  6. Post({this.userId, this.id, this.title, this.body});
  7. factory Post.fromJson(Map<String, dynamic> json) {
  8. return Post(
  9. userId: json['userId'],
  10. id: json['id'],
  11. title: json['title'],
  12. body: json['body'],
  13. );
  14. }
  15. }

Convert the http.Response to a Post

Now, update the fetchPost function to return a Future<Post>. To do so,you’ll need to:

  • Convert the response body into a json Map with the dart:convertpackage.
  • If the server returns an “OK” response with a status code of 200, convertthe json Map into a Post using the fromJson factory method.
  • If the server returns an unexpected response, throw an error
  1. Future<Post> fetchPost() async {
  2. final response =
  3. await http.get('https://jsonplaceholder.typicode.com/posts/1');
  4. if (response.statusCode == 200) {
  5. // If server returns an OK response, parse the JSON
  6. return Post.fromJson(json.decode(response.body));
  7. } else {
  8. // If that response was not OK, throw an error.
  9. throw Exception('Failed to load post');
  10. }
  11. }

Hooray! Now you’ve got a function that we can call to fetch a Post from theinternet.

4. Fetch and Display the data

In order to fetch the data and display it on screen, you can use theFutureBuilderwidget. The FutureBuilder Widget comes with Flutter and makes it easyto work with async data sources.

You must provide two parameters:

  • The Future you want to work with. In this case, call thefetchPost() function.
  • A builder function that tells Flutter what to render, depending on thestate of the Future: loading, success, or error.
  1. FutureBuilder<Post>(
  2. future: fetchPost(),
  3. builder: (context, snapshot) {
  4. if (snapshot.hasData) {
  5. return Text(snapshot.data.title);
  6. } else if (snapshot.hasError) {
  7. return Text("${snapshot.error}");
  8. }
  9. // By default, show a loading spinner
  10. return CircularProgressIndicator();
  11. },
  12. );

5. Moving the fetch call out of the build() method

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

Flutter calls the build() method every time it wants to change anythingin the view, and this happens surprisingly often. If you leave the fetchcall in your build() method, you’ll flood the API with unnecessary callsand slow down your app.

Here are some better options so it’ll only hit the API when the page isinitially loaded.

Pass it into a StatelessWidget

With this strategy, the parent widget is responsible for calling the fetchmethod, storing its result, and then passing it to your widget.

  1. class MyApp extends StatelessWidget {
  2. final Future<Post> post;
  3. MyApp({Key key, this.post}) : super(key: key);

You can see a working example of this in the complete example below.

Call it in the lifecycle of a StatefulWidget’s state

If your widget is stateful, you can call the fetch method in either theinitState ordidChangeDependenciesmethods.

initState is called exactly once and then never again.If you want to have the option of reloading the API in response to anInheritedWidgetchanging, put the call into the didChangeDependencies method. SeeState for moredetails.

  1. class _MyAppState extends State<MyApp> {
  2. Future<Post> post;
  3. @override
  4. void initState() {
  5. super.initState();
  6. post = fetchPost();
  7. }

Testing

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

Complete example

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:flutter/material.dart';
  4. import 'package:http/http.dart' as http;
  5. Future<Post> fetchPost() async {
  6. final response =
  7. await http.get('https://jsonplaceholder.typicode.com/posts/1');
  8. if (response.statusCode == 200) {
  9. // If the call to the server was successful, parse the JSON
  10. return Post.fromJson(json.decode(response.body));
  11. } else {
  12. // If that call was not successful, throw an error.
  13. throw Exception('Failed to load post');
  14. }
  15. }
  16. class Post {
  17. final int userId;
  18. final int id;
  19. final String title;
  20. final String body;
  21. Post({this.userId, this.id, this.title, this.body});
  22. factory Post.fromJson(Map<String, dynamic> json) {
  23. return Post(
  24. userId: json['userId'],
  25. id: json['id'],
  26. title: json['title'],
  27. body: json['body'],
  28. );
  29. }
  30. }
  31. void main() => runApp(MyApp(post: fetchPost()));
  32. class MyApp extends StatelessWidget {
  33. final Future<Post> post;
  34. MyApp({Key key, this.post}) : super(key: key);
  35. @override
  36. Widget build(BuildContext context) {
  37. return MaterialApp(
  38. title: 'Fetch Data Example',
  39. theme: ThemeData(
  40. primarySwatch: Colors.blue,
  41. ),
  42. home: Scaffold(
  43. appBar: AppBar(
  44. title: Text('Fetch Data Example'),
  45. ),
  46. body: Center(
  47. child: FutureBuilder<Post>(
  48. future: post,
  49. builder: (context, snapshot) {
  50. if (snapshot.hasData) {
  51. return Text(snapshot.data.title);
  52. } else if (snapshot.hasError) {
  53. return Text("${snapshot.error}");
  54. }
  55. // By default, show a loading spinner
  56. return CircularProgressIndicator();
  57. },
  58. ),
  59. ),
  60. ),
  61. );
  62. }
  63. }