November 7, 2025
Flutter

How to use http in flutter step by step guide

Here’s a step-by-step guide on how to use the http package in Flutter to make network requests (GET, POST, PUT, DELETE).
We’ll also create a simple example that fetches and displays data — perfect for a WordPress REST API or any other API.


🧩 Step 1: Add the HTTP package

Open your Flutter project’s pubspec.yaml file and add this dependency:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.2

Then run:

flutter pub get

🏗 Step 2: Import the HTTP package

In your Dart file (e.g., api_service.dart), import the package:

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

🌐 Step 3: Create a simple API service

Let’s create a service to fetch posts from a WordPress REST API.

File: lib/services/api_service.dart

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

class ApiService {
  final String baseUrl = 'https://example.com/wp-json/wp/v2';

  Future<List<dynamic>> fetchPosts() async {
    final response = await http.get(Uri.parse('$baseUrl/posts'));

    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to load posts');
    }
  }

  Future<void> createPost(String title, String content, String token) async {
    final response = await http.post(
      Uri.parse('$baseUrl/posts'),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token', // For authenticated requests
      },
      body: json.encode({
        'title': title,
        'content': content,
        'status': 'publish',
      }),
    );

    if (response.statusCode != 201) {
      throw Exception('Failed to create post');
    }
  }
}

🖥 Step 4: Use the service in your UI

Now, let’s use the service in a Flutter widget to display posts.

File: lib/screens/posts_screen.dart

import 'package:flutter/material.dart';
import '../services/api_service.dart';

class PostsScreen extends StatefulWidget {
  const PostsScreen({super.key});

  @override
  State<PostsScreen> createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen> {
  final ApiService apiService = ApiService();
  late Future<List<dynamic>> posts;

  @override
  void initState() {
    super.initState();
    posts = apiService.fetchPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('WordPress Posts')),
      body: FutureBuilder<List<dynamic>>(
        future: posts,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return const Center(child: Text('No posts found'));
          } else {
            final posts = snapshot.data!;
            return ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final post = posts[index];
                return ListTile(
                  title: Text(post['title']['rendered']),
                  subtitle: Text(
                    post['excerpt']['rendered']
                        .replaceAll(RegExp(r'<[^>]*>'), ''), // Remove HTML tags
                  ),
                );
              },
            );
          }
        },
      ),
    );
  }
}

⚙️ Step 5: Update main.dart

Run your app and set the PostsScreen as the home screen:

import 'package:flutter/material.dart';
import 'screens/posts_screen.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HTTP Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const PostsScreen(),
    );
  }
}

✅ Step 6: Run the app

Run your Flutter app:

flutter run

You’ll see a list of posts fetched from your WordPress API.


📚 Optional — Other HTTP Methods

PUT (Update Post)

Future<void> updatePost(int id, String title, String token) async {
  final response = await http.put(
    Uri.parse('$baseUrl/posts/$id'),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $token',
    },
    body: json.encode({'title': title}),
  );

  if (response.statusCode != 200) {
    throw Exception('Failed to update post');
  }
}

DELETE (Delete Post)

Future<void> deletePost(int id, String token) async {
  final response = await http.delete(
    Uri.parse('$baseUrl/posts/$id'),
    headers: {'Authorization': 'Bearer $token'},
  );

  if (response.statusCode != 200) {
    throw Exception('Failed to delete post');
  }
}

🎯 Summary

✅ Add http dependency
✅ Create a service class
✅ Use GET, POST, PUT, DELETE
✅ Display data with FutureBuilder

Related posts

What is bloc and how to use in flutter application step by step guide

Dheeraj Pal

How to use WebSocket in flutter step by step guide

Dheeraj Pal

Appointment Booking for Doctor Using Flutter

Dheeraj Pal

2 comments

How to use firebase in flutter - Dheeraj Hitech November 1, 2025 at 7:29 pm

[…] How to use http in flutter step by step guide […]

Reply
How to create login and signup page using flutter - Dheeraj Hitech November 1, 2025 at 7:32 pm

[…] How to use http in flutter step by step guide […]

Reply

Leave a Comment