free geoip
48

How to Fetch Data from API in Dart Easily

Fetching data from an API is a fundamental skill in modern app development. In Dart, especially when using Flutter, the…

Fetching data from an API is a fundamental skill in modern app development. In Dart, especially when using Flutter, the http package makes it easy to send HTTP requests and parse JSON responses. This guide will show you how to fetch data from a REST API using Dart, parse the response, and display it effectively.

Fetch Data from API in Dart

💡 Before getting started, make sure you’ve added the http package in your pubspec.yaml file:

dependencies:
  http: ^0.13.0

1. Create a Model Class

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'],
    );
  }
}

2. Fetch Data from the API

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'post_model.dart'; // Model file above

Future<List<Post>> fetchPosts() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    List<dynamic> body = jsonDecode(response.body);
    return body.map((json) => Post.fromJson(json)).toList();
  } else {
    throw Exception('Failed to load posts');
  }
}

3. Use in a Dart/Flutter App

You can now use the fetchPosts() function in your main UI to display data asynchronously using FutureBuilder (in Flutter) or manually call it in console-based Dart apps.

Example usage in Dart console:

void main() async {
  List<Post> posts = await fetchPosts();
  for (var post in posts) {
    print('${post.id}: ${post.title}');
  }
}

External Resource:

You can read more about using the http package in Dart on the Dart.dev documentation.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *