Enable Dark Mode!
how-to-integrate-restful-apis-in-flutter-applications.jpg
By: Sreerag PM

How to Integrate RESTful APIs in Flutter Applications

Technical Flutter

Flutter, Google's UI toolkit, is known for its capability to build high-quality, cross-platform applications for mobile, web, and desktop from a single codebase. One of the most common tasks in app development is integrating RESTful APIs to fetch and send data over the internet. In this blog, we'll walk through how to integrate RESTful APIs into your Flutter applications.

Why Use RESTful APIs?

RESTful APIs provide a consistent approach for interacting with web resources through standard HTTP operations. By integrating REST APIs, Flutter applications can communicate with external services to support features such as secure user login, seamless data synchronization, and dynamic content updates.

Prerequisites

Before we dive into coding, ensure you have the following setup:

  • Flutter SDK installed
  • A basic understanding of Dart programming
  • An IDE like Android Studio, VSCode, or IntelliJ IDEA
  • A REST API endpoint to interact with (for this tutorial, we'll use a sample JSON placeholder API

Step 1: Setting Up Your Flutter Project

Open your terminal and run the following commands to create a new Flutter project:

flutter create rest_api_example
cd rest_api_example

Open the project in your preferred IDE.

Step 2: Adding Dependencies

To handle HTTP requests, we'll use the http package. Open pubspec.yaml and add the following under dependencies:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0

Run flutter pub get to install the package.

Step 3: Creating a Model Class

Create a new file called post.dart in the lib directory to define the data model.

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;
  Post({required this.userId, required this.id, required this.title, required this.body});
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }

Step 4: Fetching Data from the API

Create a new file called api_service.dart in the lib directory to handle API requests.

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'post.dart';
class ApiService {
  final String apiUrl = "https://jsonplaceholder.typicode.com/posts";
  Future<List<Post>> fetchPosts() async {
    final response = await http.get(Uri.parse(apiUrl));
    if (response.statusCode == 200) {
      List<dynamic> body = jsonDecode(response.body);
      return body.map((dynamic item) => Post.fromJson(item)).toList();
    } else {
      throw Exception("Failed to load posts");
    }
  }
}

Step 5: Displaying Data in the UI

Open lib/main.dart and update it to fetch and display data.

import 'package:flutter/material.dart';
import 'api_service.dart';
import 'post.dart';
void main() { 
  runApp(const MyApp()); 
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'REST API Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: PostListScreen(),
    );
  }
}
class PostListScreen extends StatefulWidget {
  @override
  _PostListScreenState createState() => _PostListScreenState();
}
class _PostListScreenState extends State<PostListScreen> {
  late Future<List<Post>> futurePosts;
  @override
  void initState() {
    super.initState();
    futurePosts = ApiService().fetchPosts();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Posts')),
      body: FutureBuilder<List<Post>>(
        future: futurePosts,
        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 || snapshot.data!.isEmpty) {
            return Center(child: Text('No posts found'));
          }
          return ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(snapshot.data![index].title),
                subtitle: Text(snapshot.data![index].body),
              );
            },
          );
        },
      ),
    );
  }
}

Step 6: Running the Application

Save all files and run the app using the following command:

flutter run

You should see a list of posts fetched from the JSON placeholder API displayed in your app.

Conclusion

Integrating RESTful APIs in Flutter is straightforward with the help of the http package. By following the steps above, you can fetch, parse, and display data in your Flutter applications. You can further extend this example by adding POST, PUT, and DELETE methods to handle different API operations.

To read more about How to Add Smooth and Engaging Animations in Flutter, refer to our blog How to Add Smooth and Engaging Animations in Flutter.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message