Working with APIs in Flutter: Fetching and Displaying Data
APIs (Application Programming Interfaces) are the backbone of modern mobile apps, enabling them to communicate with servers and fetch real-time data. In Flutter, working with APIs is straightforward thanks to powerful libraries like http. Whether you’re building a weather app or a product list, understanding how to fetch and display data from an API is a key skill.
🛠️ Step 1: Add the http Package
To get started, include the http package in your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
http: ^0.13.6
Run flutter pub get to install the package.
🌐 Step 2: Make an API Call
Create a function to fetch data from a sample API. For example, let’s use a placeholder API that returns a list of users.
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List<dynamic>> fetchUsers() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load users');
}
}
🧩 Step 3: Display the Data in Your App
Use a FutureBuilder widget to call the function and display the results.
import 'package:flutter/material.dart';
class UserListPage extends StatelessWidget {
const UserListPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User List')),
body: FutureBuilder<List<dynamic>>(
future: fetchUsers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
final users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return ListTile(
title: Text(user['name']),
subtitle: Text(user['email']),
);
},
);
}
},
),
);
}
}
✅ Tips for Better API Integration
Use model classes to map JSON data (via json_serializable or manual parsing).
Handle errors and timeouts gracefully.
Use tools like Dio for advanced network handling.
Secure API keys using environment variables or Flutter secure storage.
🧾 Conclusion
Fetching and displaying data from an API in Flutter is a fundamental skill for mobile developers. With the http package and FutureBuilder, you can easily integrate dynamic data into your app, making it interactive and powerful. Once mastered, you can expand to more advanced topics like pagination, authentication, and state management.
Learn Flutter Training in Hyderabad
Read More:
Using Flutter for Cross-Platform Mobile Development
Customizing Flutter Widgets: Tips and Tricks
Handling User Input and Forms in Flutter
Building a Chat App with Flutter and Firebase
Flutter vs React Native: Which One Should You Learn?
Visit our IHub Talent Training Institute
Comments
Post a Comment