smart_fetch 1.0.2 copy "smart_fetch: ^1.0.2" to clipboard
smart_fetch: ^1.0.2 copied to clipboard

Beautiful full-screen error pages for server side errors and no internet connection state.

SmartFetch #

pub package License: MIT

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!

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 connectivity
  • ServerErrorScreen - Shown when server returns an error
  • TimeoutScreen - 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.Response
  • timeout: 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.Response
  • onSuccess: Widget builder called when request succeeds
  • loadingWidget: Optional custom loading widget
  • timeout: Optional timeout duration (default: 10 seconds)

SmartFetchNavigator #

Helper class with static methods for navigating to error screens:

  • showNoInternet(context) - Show no internet screen
  • showServerError(context) - Show server error screen
  • showTimeout(context) - Show timeout screen
  • showErrorScreen(context, result) - Automatically show correct screen
  • showErrorScreenWithKey(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 screen
  • ServerErrorScreen() - Server error screen
  • TimeoutScreen() - 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
3
likes
0
points
492
downloads

Publisher

unverified uploader

Weekly Downloads

Beautiful full-screen error pages for server side errors and no internet connection state.

Repository (GitHub)
View/report issues

Topics

#flutter #error-handling #timeout #no-internet #server-error

License

unknown (license)

Dependencies

connectivity_plus, flutter, http, lottie

More

Packages that depend on smart_fetch