Sitemap
Omid Kzm

Omid Kzm

Networking

2 min readAug 7, 2023

Here’s an example of how to integrate your Flutter app with APIs and web services using the http package for fetching and sending data:

Get Omid Kzm’s stories in your inbox

Join Medium for free to get updates from this writer.

1. Add the necessary dependencies to your pubspec.yaml:

dependencies:
flutter:
sdk: flutter
http: ^0.13.3

2. Create a new Dart file for your app:

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

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'API Integration Sample',
theme: ThemeData(primarySwatch: Colors.blue),
home: HomeScreen(),
);
}
}

class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
List<String> _posts = [];

Future<void> _fetchPosts() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
final List<String> posts = data.map((item) => item['title'] as String).toList();
setState(() {
_posts = posts;
});
} else {
throw Exception('Failed to load posts');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Integration Sample')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _fetchPosts,
child: Text('Fetch Posts'),
),
SizedBox(height: 20),
if (_posts.isNotEmpty)
Column(
children: _posts
.map((post) => ListTile(
title: Text(post),
))
.toList(),
),
],
),
),
);
}
}

In this example:

- The _fetchPosts function uses the http package to send a GET request to a sample API endpoint (https://jsonplaceholder.typicode.com/posts) that returns a list of posts.
- If the response status code is 200 (OK), the data is parsed using json.decode and displayed in the UI.
- The UI displays a button that triggers the API call and a list of fetched posts when available.

This example demonstrates how to use the http package to fetch data from an API. You can adapt this pattern to handle various API requests, error handling, request headers, and more complex scenarios. Additionally, you can explore using other packages like dio for more advanced API interactions with features like request cancellation, interceptors, and FormData handling.

--

--