Codementor Events

Flutter and RESTful APIs: A Comprehensive Exploration for Developers

Published Jul 10, 2023
Flutter and RESTful APIs: A Comprehensive Exploration for Developers

Greetings, aspiring Flutter developers! Today, we're exploring an essential aspect of modern application development: integrating with a RESTful API. By the end of this guide, you'll have a solid understanding of how to retrieve, display, and manage data from a RESTful API using Flutter, adding crucial skills to your Flutter development repertoire.

Unveiling RESTful APIs

REST, an acronym for Representational State Transfer, is a widely-used architectural style for designing networked applications. In a RESTful API, the server maintains and manages resources, which can be anything from data objects to services. Clients interact with these resources via standard HTTP methods, such as GET, POST, PUT, DELETE.

Building an Advanced Flutter App with RESTful API Integration

To illustrate this, we'll develop a Flutter application that retrieves, displays, and deletes posts from the JSONPlaceholder API, a simple, freely available API for testing and prototyping.

Kick-starting the App
Create a new Flutter application:

flutter create flutter_api_demo
cd flutter_api_demo

In your pubspec.yaml file, add the http package, which we'll use to make HTTP requests:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

Run flutter packages get to install the package.

Building API Service

In a new api_service.dart file, let's establish our API interactions.

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

class ApiService {
  final String _baseUrl = "https://jsonplaceholder.typicode.com";

  Future<List<dynamic>> getPosts() async {
    final response = await http.get(Uri.parse("$_baseUrl/posts"));

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

  Future<void> deletePost(int id) async {
    final response = await http.delete(Uri.parse("$_baseUrl/posts/$id"));

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

Our getPosts() method fetches posts from the API, while the deletePost() method deletes a specific post by ID.

Crafting UI and Connecting API

Now let's build our UI and link it with our API. Replace the existing code in main.dart with the following:

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

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

class MyApp extends StatelessWidget {
  final ApiService apiService = ApiService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter REST API',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text("Posts"),
        ),
        body: FutureBuilder(
          future: apiService.getPosts(),
          builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  var post = snapshot.data[index];
                  return ListTile(
                    title: Text(post['title']),
                    subtitle: Text(post['body']),
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () async {
                        await apiService.deletePost(post['id']);
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('Post with id ${post['id']} deleted.')),
                        );
                        setState(() {});
                      },
                    ),
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

In the code above, FutureBuilder asynchronously fetches posts from the API and builds a ListView with the data. Each ListTile in the ListView displays the title and body of a post and includes a delete button that calls the deletePost() method when pressed.

Taking the App for a Spin

It's time to run your application. Use the following command:

flutter run

You should see a list of posts from the JSONPlaceholder API. Each list item contains a post's title, body, and a delete button to remove the post.

Deep Dive Conclusion

By integrating a RESTful API into your Flutter application, you can create dynamic, data-driven applications. The principles discussed here – retrieving, displaying, and deleting data from an API – form the backbone of many modern applications. With this knowledge, you can extend your Flutter applications to interact with a wide variety of APIs, allowing you to build more complex and interactive applications.

Are you planning to create a Flutter application or need some guidance with Flutter development? Feel free to contact me. With my comprehensive understanding of Flutter and RESTful APIs, I can help bring your project to fruition.

Discover and read more posts from Basel Farag
get started
post commentsBe the first to share your opinion
Ron
a month ago

If you’re diving into Flutter and RESTful APIs on CodeMentor, enrich your learning by exploring the Electron vs Flutter comparison that is https://wegile.com/insights/electron-vs-flutter.php. This resource provides a detailed look at choosing the right framework for your project, a crucial decision in app development.

Show more replies