smart_fetch 1.0.2
smart_fetch: ^1.0.2 copied to clipboard
Beautiful full-screen error pages for server side errors and no internet connection state.
SmartFetch #
A Flutter package that provides beautiful full-screen error pages and intelligent handling for server-side errors, no internet connection states, and timeouts. SmartFetch simplifies error handling in your Flutter applications with ready-to-use widgets and utilities.
Features #
β¨ Automatic Error Detection: Distinguishes between no internet, server errors, and timeouts
π¨ Beautiful Error Screens: Pre-built, animated full-screen error pages using Lottie animations
π Easy Integration: Simple API with both programmatic and widget-based approaches
π― Type-Safe Results: Strongly-typed result objects for clean error handling
π± Accessible Error Screens: Use predefined screens directly or via helper methods
π Connectivity Aware: Real-time internet connectivity checking
π Flexible Usage: Three ways to use error screens - automatic, helper methods, or direct access
Getting Started #
Add smart_fetch to your pubspec.yaml:
dependencies:
smart_fetch: ^1.0.2
http: ^1.6.0
Then run:
flutter pub get
Quick Start #
Method 1: Automatic Error Screens (Easiest) #
Error screens are shown automatically with SmartFetch.builder():
import 'package:smart_fetch/smart_fetch.dart';
import 'package:http/http.dart' as http;
SmartFetch.builder(
future: () => http.get(Uri.parse('https://api.example.com/data')),
onSuccess: (context, response) => Text('Success: ${response.body}'),
loadingWidget: CircularProgressIndicator(),
)
// Error screens show automatically!
Method 2: Using Helper Methods (Recommended) #
Use SmartFetchNavigator for easy navigation to error screens:
import 'package:smart_fetch/smart_fetch.dart';
import 'package:http/http.dart' as http;
final result = await SmartFetch.call(
() => http.get(Uri.parse('https://api.example.com/data')),
);
// One line to show the correct error screen
SmartFetchNavigator.showErrorScreen(context, result);
// Or show specific screens
SmartFetchNavigator.showNoInternet(context);
SmartFetchNavigator.showServerError(context);
SmartFetchNavigator.showTimeout(context);
Method 3: Direct Screen Access #
Import and use error screens directly:
import 'package:smart_fetch/smart_fetch.dart';
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const NoInternetScreen()),
);
Usage Examples #
Basic API Call with Error Handling #
Option 1: When you have BuildContext (in a Widget)
import 'package:smart_fetch/smart_fetch.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
Future<void> fetchData(BuildContext context) async {
final result = await SmartFetch.call(
() => http.get(Uri.parse('https://api.example.com/data')),
timeout: const Duration(seconds: 10),
);
if (result.isSuccess) {
print('Success: ${result.response?.body}');
} else {
// Use helper method - automatically shows correct screen
SmartFetchNavigator.showErrorScreen(context, result);
}
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => fetchData(context),
child: Text('Fetch Data'),
);
}
}
Option 2: When you don't have BuildContext (Service Classes)
Use a global navigator key and pass it to the helper methods:
// In main.dart
final navigatorKey = GlobalKey<NavigatorState>();
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey, // Add this
home: HomeScreen(),
);
}
}
// In your service class
import 'package:smart_fetch/smart_fetch.dart';
import 'package:http/http.dart' as http;
import 'main.dart'; // Import to access navigatorKey
class ApiService {
static Future<void> fetchData() async {
final result = await SmartFetch.call(
() => http.get(Uri.parse('https://api.example.com/data')),
);
if (result.isSuccess) {
print('Success: ${result.response?.body}');
} else {
// Use navigator key to show error screen
SmartFetchNavigator.showErrorScreenWithKey(navigatorKey, result);
}
}
}
Widget-Based Integration #
import 'package:flutter/material.dart';
import 'package:smart_fetch/smart_fetch.dart';
import 'package:http/http.dart' as http;
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SmartFetch Example')),
body: SmartFetch.builder(
future: () => http.get(Uri.parse('https://api.example.com/data')),
onSuccess: (context, response) {
return Center(
child: Text('Data: ${response.body}'),
);
},
loadingWidget: Center(
child: CircularProgressIndicator(),
),
timeout: Duration(seconds: 10),
),
);
}
}
Using Error Screens in Service Classes (No Context Needed!) #
Perfect for service classes where you don't have BuildContext:
Step 1: Create navigator key in main.dart
final navigatorKey = GlobalKey<NavigatorState>();
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: HomeScreen(),
);
}
}
Step 2: Use in service class with navigator key
// In your service class
import 'main.dart'; // Import to access navigatorKey
final result = await SmartFetch.call(
() => http.post(Uri.parse(apiUrl), body: body),
);
if (result.isSuccess) {
// Handle success
} else {
// Show error screen using navigator key
SmartFetchNavigator.showErrorScreenWithKey(navigatorKey, result);
}
Manual Connectivity Check #
import 'package:smart_fetch/smart_fetch.dart';
final hasInternet = await InternetChecker.hasInternet();
if (hasInternet) {
// Proceed with API call
} else {
SmartFetchNavigator.showNoInternet(context);
}
Available Error Screens #
The package provides three pre-built error screens:
NoInternetScreen- Shown when device has no internet connectivityServerErrorScreen- Shown when server returns an errorTimeoutScreen- Shown when request exceeds timeout duration
All screens include:
- Beautiful Lottie animations
- Clear error messages
- "Try Again" button for easy retry
API Reference #
SmartFetch.call() #
Makes an HTTP request with automatic error handling.
Parameters:
request: A function that returns a Future of http.Responsetimeout: Optional timeout duration (default: 10 seconds)
Returns: SmartFetchResult with status and response data
SmartFetch.builder() #
A widget builder that automatically handles loading, success, and error states.
Parameters:
future: A function that returns a Future of http.ResponseonSuccess: Widget builder called when request succeedsloadingWidget: Optional custom loading widgettimeout: Optional timeout duration (default: 10 seconds)
SmartFetchNavigator #
Helper class with static methods for navigating to error screens:
showNoInternet(context)- Show no internet screenshowServerError(context)- Show server error screenshowTimeout(context)- Show timeout screenshowErrorScreen(context, result)- Automatically show correct screenshowErrorScreenWithKey(navigatorKey, result)- Use with global navigator key
All methods support an optional replace parameter to replace the current route.
Error Screens #
Direct access to error screen widgets:
NoInternetScreen()- No internet connection screenServerErrorScreen()- Server error screenTimeoutScreen()- Timeout screen
Example #
Check out the complete example in the /example folder:
cd example
flutter run
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments #
- Uses Lottie for beautiful animations
- Uses connectivity_plus for network detection
- Built with β€οΈ for the Flutter community