Integrating REST APIs in Flutter

 Integrating REST APIs into a Flutter app allows you to fetch, send, and manipulate data from web services, enabling dynamic and interactive mobile apps. Whether you’re building a social media feed, weather app, or e-commerce platform, connecting to APIs is a fundamental skill for any Flutter developer.

Choose the Right Package

The most popular package for HTTP requests in Flutter is the http package. Add it to your pubspec.yaml:

dependencies:

  http: ^1.0.0

Then, run flutter pub get.

Fetching Data

To fetch data, import http and use the get method:

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

import 'dart:convert';

Future<List<dynamic>> fetchPosts() async {

  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {

    return json.decode(response.body);

  } else {

    throw Exception('Failed to load posts');

  }

}

Displaying Data

Use a FutureBuilder widget to fetch and display data asynchronously in your Flutter UI:

FutureBuilder<List<dynamic>>(

  future: fetchPosts(),

  builder: (context, snapshot) {

    if (snapshot.hasData) {

      return ListView.builder(

        itemCount: snapshot.data!.length,

        itemBuilder: (context, index) {

          return ListTile(

            title: Text(snapshot.data![index]['title']),

          );

        },

      );

    } else if (snapshot.hasError) {

      return Center(child: Text('Error: ${snapshot.error}'));

    }

    return Center(child: CircularProgressIndicator());

  },

)

Sending Data

To send data (e.g., creating a new post), use the post method:

Future<void> createPost(String title, String body) async {

  final response = await http.post(

    Uri.parse('https://jsonplaceholder.typicode.com/posts'),

    headers: {'Content-Type': 'application/json'},

    body: json.encode({'title': title, 'body': body}),

  );

  if (response.statusCode == 201) {

    print('Post created successfully');

  } else {

    throw Exception('Failed to create post');

  }

}

Error Handling

Always handle exceptions with try-catch to improve user experience and stability:

try {

  await createPost('Hello', 'This is a new post');

} catch (e) {

  print('Error: $e');

}

Next Steps

For more advanced use cases, consider packages like dio for more features (e.g., interceptors, advanced error handling) and using provider or bloc for state management to update your UI seamlessly.

Integrating REST APIs in Flutter bridges your app with the outside world, unlocking endless possibilities for creating data-driven, real-time applications.

Learn Flutter Training Course

Read More:

Using Firebase with Flutter

Creating Beautiful UI with Flutter

Handling User Input in Flutter

Flutter Layouts: Row, Column, Stack

Visit Quality Thought Training Institute

Get Direction

Comments

Popular posts from this blog

DevOps vs Agile: Key Differences Explained

How to Set Up a MEAN Stack Development Environment

Regression Analysis in Python