API Calls in Flutter Using Provider
Why Use Provider for API Calls?
When building Flutter apps, managing API calls efficiently is crucial. Provider simplifies this by handling state management and ensuring smooth UI updates.
In this blog, we'll learn how to use Provider for API calls, fetching data from a remote server and displaying it in a Flutter app. Let's dive in!
Setting Up Dependencies
First, add the required packages to your project:
flutter pub add provider http
provider
: Manages state efficiently.http
: Helps in making network requests.
Creating API Service Class
This class will handle the API requests.
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
Future<List<dynamic>> fetchPosts() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception("Failed to load posts");
}
}
}
📌 This function fetches data from a fake API and returns a list of posts.
Creating Provider Class
We'll now create a PostProvider
class that fetches data and notifies listeners when data is updated.
import 'package:flutter/material.dart';
import 'api_service.dart';
class PostProvider with ChangeNotifier {
List<dynamic> _posts = [];
bool _isLoading = false;
List<dynamic> get posts => _posts;
bool get isLoading => _isLoading;
final ApiService _apiService = ApiService();
Future<void> fetchPosts() async {
_isLoading = true;
notifyListeners();
try {
_posts = await _apiService.fetchPosts();
} catch (e) {
print("Error: $e");
} finally {
_isLoading = false;
notifyListeners();
}
}
}
Registering Provider in main.dart
We need to wrap our app inside MultiProvider
to make PostProvider
accessible.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'post_provider.dart';
import 'home_screen.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => PostProvider()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
This makes sure PostProvider
is available throughout the app.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'post_provider.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final postProvider = Provider.of<PostProvider>(context);
return Scaffold(
appBar: AppBar(title: Text("API Call with Provider")),
body: Column(
children: [
ElevatedButton(
onPressed: () {
postProvider.fetchPosts();
},
child: Text("Fetch Posts"),
),
Expanded(
child: postProvider.isLoading
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: postProvider.posts.length,
itemBuilder: (context, index) {
final post = postProvider.posts[index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);
},
),
),
],
),
);
}
}
📌 This UI provides a Fetch Posts button that loads data and displays it in a list.
🔥 Final Thoughts
🎯 Why use Provider for API calls? ✅ Separates UI from business logic.
✅ Automatically updates UI when data changes.
✅ Reduces complexity and improves performance.
If you want to explore more advanced state management, check out our Advanced Provider Guide. 🚀
Let me know if you have any questions! 😃 Happy Coding! 🔥
Comments
Post a Comment