Blog Details

img
Development

Flutter – Fetching Data From the Internet

Spoke Right / 1 Nov, 2023

In today’s world, most applications heavily rely on fetching 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 fetch data from the internet follow the below steps:

  1. Import the http package
  2. Make a network request using the http package
  3. Convert the response into custom Dart object
  4. Display the data in a suitable format

Importing The http Package:

To install the http package use the below command in your command prompt:

pub get

or, if you are using the flutter cmd use the below command:

flutter pub get

dependencies

After the installation add the dependency to the pubsec.yml file as shown below:

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

Requesting Data:

We can use the http.get() method to fetch the sample album data from JSONPlaceholder as shown below:

  • Dart




Future fetchAlbum() {

  return http.get('https://jsonplaceholder.typicode.com/albums/1');

}

Converting the Response:

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 userId;

  final int id;

  final String title;


  Album({this.userId, this.id, this.title});


  factory Album.fromJson(Map json) {

    return Album(

      userId: json['userId'],

      id: json['id'],

      title: json['title'],

    );

  }

}

Convert http.Response to an Album:

Now, follow the below steps to update the fetchAlbum() function to return a Future:

  1. Use the dart: convert package to convert the response body into a JSON Map.
  2. Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.
  3. Throw an exception if the server doesn’t return an OK response with a status code of 200.
  • Dart




Future 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');

  }

}

 

Fetching the Data:


Now use the fetch() method to fetch the data as shown below:


  • Dart




class _MyAppState extends State {

  Future futureAlbum;


  @override

  void initState() {

    super.initState();

    futureAlbum = fetchAlbum();

  }

Displaying the Data:

Use the FlutterBuilder widget to display the data on the screen as shown below:

  • Dart




FutureBuilder(

  future: futureAlbum,

  builder: (context, snapshot) {

    if (snapshot.hasData) {

      return Text(snapshot.data.title);

    } else if (snapshot.hasError) {

      return Text("${snapshot.error}");

    }


    // spinner

    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 fetchAlbum() async {

  final response =

      await http.get('https://jsonplaceholder.typicode.com/albums/1');


  // Appropriate action depending upon the

  // server response

  if (response.statusCode == 200) {

    return Album.fromJson(json.decode(response.body));

  } else {

    throw Exception('Failed to load album');

  }

}


class Album {

  final int userId;

  final int id;

  final String title;


  Album({this.userId, this.id, this.title});


  factory Album.fromJson(Map json) {

    return Album(

      userId: json['userId'],

      id: json['id'],

      title: json['title'],

    );

  }

}


void main() => runApp(MyApp());


class MyApp extends StatefulWidget {

  MyApp({Key key}) : super(key: key);


  @override

  _MyAppState createState() => _MyAppState();

}


class _MyAppState extends State {

  Future futureAlbum;


  @override

  void initState() {

    super.initState();

    futureAlbum = fetchAlbum();

  }


  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Fetching Data',

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

      home: Scaffold(

        appBar: AppBar(

          title: Text('GeeksForGeeks'),

        ),

        body: Center(

          child: FutureBuilder(

            future: futureAlbum,

            builder: (context, snapshot) {

              if (snapshot.hasData) {

                return Text(snapshot.data.title);

              } else if (snapshot.hasError) {

                return Text("${snapshot.error}");

              }

              return CircularProgressIndicator();

            },

          ),

        ),

      ),

    );

  }

}

Output:

fetched data from the internet

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0