How to Fetch Data from APIs in Flutter

In the modern mobile app world, data is everything. Whether you're building a weather app, a news reader, or a social media platform, fetching data from a REST API is often one of the first things you’ll need to implement. Fortunately, Flutter, Google’s UI toolkit for building beautiful apps, makes working with APIs both simple and powerful.

In this blog, we’ll walk through how to fetch data from an API in Flutter using Dart’s built-in http package, and display it using widgets in a clean and efficient way.


🚀 Prerequisites

Before diving in, make sure you have:

Flutter SDK installed

A working Flutter project

Internet permission (required for Android/iOS)

Basic understanding of Dart and widgets


📦 Step 1: Add the http Package

To fetch data from the internet, you’ll use the http package. Add this to your pubspec.yaml:

yaml

dependencies:

  http: ^0.13.6

Run flutter pub get to install the package.


🌐 Step 2: Choose an API Endpoint

Let’s use a free sample API for demonstration:

API Endpoint: https://jsonplaceholder.typicode.com/posts

This returns a list of post objects in JSON format.


🧱 Step 3: Create a Data Model

Define a Dart class to map the JSON response:

dart



class Post {

  final int id;

  final String title;

  final String body;


  Post({required this.id, required this.title, required this.body});


  factory Post.fromJson(Map<String, dynamic> json) {

    return Post(

      id: json['id'],

      title: json['title'],

      body: json['body'],

    );

  }

}


🔄 Step 4: Fetch Data with http.get()

Use the http package to fetch the API data:


dart


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

import 'dart:convert';


Future<List<Post>> fetchPosts() async {

  final response =

      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));


  if (response.statusCode == 200) {

    List jsonData = json.decode(response.body);

    return jsonData.map((item) => Post.fromJson(item)).toList();

  } else {

    throw Exception('Failed to load posts');

  }

}

🧩 Step 5: Display Data in a Flutter Widget

Use FutureBuilder to show the API data once it’s fetched:

dart



import 'package:flutter/material.dart';


class PostsPage extends StatelessWidget {

  const PostsPage({Key? key}) : super(key: key);


  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: Text('Posts')),

      body: FutureBuilder<List<Post>>(

        future: fetchPosts(),

        builder: (context, snapshot) {

          if (snapshot.hasData) {

            List<Post> posts = snapshot.data!;

            return ListView.builder(

              itemCount: posts.length,

              itemBuilder: (context, index) => ListTile(

                title: Text(posts[index].title),

                subtitle: Text(posts[index].body),

              ),

            );

          } else if (snapshot.hasError) {

            return Center(child: Text('Error: ${snapshot.error}'));

          }

          return Center(child: CircularProgressIndicator());

        },

      ),

    );

  }

}

✅ Best Practices

Use error handling for failed network calls

Use caching or state management for performance

Use environment variables to store API URLs securely

Consider using packages like Dio for advanced network handling


🏁 Final Thoughts

Fetching data from an API is a core skill in Flutter development. With tools like the http package and Flutter’s flexible widget system, you can easily connect your app to the real world. Whether it’s a public API or your own backend, this pattern will get you up and running quickly.

Want to go further? Try integrating authentication headers, pagination, or GraphQL APIs in your Flutter app!


Learn : Master Flutter Development with Expert Training

Read More:  Flutter State Management: setState vs Provider vs Bloc
Read More:  Flutter Layouts: Row, Column, Stack Explained
Read More:  How to Use Flutter Hot Reload for Faster Development


Visit our IHUB Talent training in Hyderabad
Get Direction

Comments

Popular posts from this blog

How to Use Tosca's Test Configuration Parameters

Using Hibernate ORM for Fullstack Java Data Management

Creating a Test Execution Report with Charts in Playwright