thumnail

Using HTTP Package to Fetch Data from API in Flutter

Thu, April 2025 22:19:40

Using HTTP Package to Fetch Data from API in Flutter

Flutter provides the http package to fetch data from an API. Here are the steps:

1. Installing the HTTP Package

Add the http dependency to pubspec.yaml:

dependencies:
  http: ^0.13.6

Then run flutter pub get to install the package.

2. Creating a Data Model

For example, if we want to fetch a list of users from the JSONPlaceholder API:

class User {
  final int id;
  final String name;
  final String email;

  User({required this.id, required this.name, required this.email});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
    );
  }
}

3. Fetching Data from API

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

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

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

4. Displaying Data in UI

import 'package:flutter/material.dart';

class UserScreen extends StatefulWidget {
  @override
  _UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
  late Future<List<User>> futureUsers;

  @override
  void initState() {
    super.initState();
    futureUsers = fetchUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Users')),
      body: FutureBuilder<List<User>>(
        future: futureUsers,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(snapshot.data![index].name),
                  subtitle: Text(snapshot.data![index].email),
                );
              },
            );
          } else {
            return Center(child: Text('No data available'));
          }
        },
      ),
    );
  }
}

CRUD Firebase Firestore in Flutter

Firestore is Firebase's NoSQL database, commonly used in Flutter applications.

1. Installing Firebase

Add the following dependencies to pubspec.yaml:

dependencies:
  firebase_core: latest_version
  cloud_firestore: latest_version

Configure Firebase using FlutterFire CLI.

2. Configuring Firebase

Add the following code in main.dart:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

3. CRUD Operations with Firestore

Adding Data

import 'package:cloud_firestore/cloud_firestore.dart';

void addUser(String name, String email) {
  FirebaseFirestore.instance.collection('users').add({
    'name': name,
    'email': email,
  });
}

Fetching Data

Stream<List<Map<String, dynamic>>> getUsers() {
  return FirebaseFirestore.instance.collection('users').snapshots().map(
      (snapshot) =>
          snapshot.docs.map((doc) => doc.data()).toList());
}

Updating Data

void updateUser(String userId, String newName) {
  FirebaseFirestore.instance
      .collection('users')
      .doc(userId)
      .update({'name': newName});
}

Deleting Data

void deleteUser(String userId) {
  FirebaseFirestore.instance.collection('users').doc(userId).delete();
}

Storing Local Data in Flutter with SharedPreferences and Hive

SharedPreferences (Simple Key-Value Storage)

Installation Add the following to pubspec.yaml:

dependencies:
  shared_preferences: latest_version

Saving and Retrieving Data

import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveData(String key, String value) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
}

Future<String?> getData(String key) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString(key);
}

Hive (Faster NoSQL Local Database than SharedPreferences)

Installation Add the following to pubspec.yaml:

dependencies:
  hive: latest_version
  hive_flutter: latest_version

dev_dependencies:
  hive_generator: latest_version
  build_runner: latest_version

Configuring Hive

import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('myBox');
  runApp(MyApp());
}

Saving and Retrieving Data

var box = Hive.box('myBox');

// Save data
box.put('username', 'JohnDoe');

// Retrieve data
String username = box.get('username', defaultValue: 'Guest');
print(username);

Conclusion

Which topic would you like to explore further? 😊