easy_api_call 0.0.4
easy_api_call: ^0.0.4 copied to clipboard
A reusable HTTP API service with token management.
example/lib/main.dart
import 'package:easy_api_call/easy_api_call.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const PostApp());
}
/// Root widget for the demo app
class PostApp extends StatelessWidget {
const PostApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'API Service Example',
home: const PostListScreen(),
debugShowCheckedModeBanner: false,
);
}
}
/// A screen that displays a list of posts fetched using ApiService
class PostListScreen extends StatefulWidget {
const PostListScreen({super.key});
@override
State<PostListScreen> createState() => _PostListScreenState();
}
class _PostListScreenState extends State<PostListScreen> {
List<dynamic> _posts = [];
bool _isLoading = true;
String? _error;
@override
void initState() {
super.initState();
_fetchPosts();
}
/// Initializes the API service and makes a GET request
Future<void> _fetchPosts() async {
try {
// Configure API service with public base URL
ApiService().configure(baseUrl: 'https://jsonplaceholder.typicode.com');
// Make GET request to /posts (no auth required)
final response = await ApiService().get('/posts');
setState(() {
_posts = response.data;
_isLoading = false;
});
} catch (e) {
setState(() {
_error = e.toString();
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Posts'),
centerTitle: true,
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _error != null
? Center(child: Text('Error: $_error'))
: ListView.separated(
itemCount: _posts.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, index) {
final post = _posts[index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);
},
),
);
}
}