client_network_manager 1.0.7 copy "client_network_manager: ^1.0.7" to clipboard
client_network_manager: ^1.0.7 copied to clipboard

A comprehensive Flutter network manager package with authentication, interceptors, and error handling support.

example/lib/main.dart

import 'package:app_logger_manager/app_logger_manager.dart';
import 'package:client_network_manager/client_network_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_connectivity_manager/flutter_connectivity_manager.dart';

import 'pages/network_demo_page.dart';
import 'services/example_network_service.dart';

void main() {
  runApp(const ClientNetworkManagerExampleApp());
}

class ClientNetworkManagerExampleApp extends StatelessWidget {
  const ClientNetworkManagerExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Client Network Manager Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          brightness: Brightness.light,
        ),
      ),
      home: const NetworkManagerSetupPage(),
    );
  }
}

class NetworkManagerSetupPage extends StatefulWidget {
  const NetworkManagerSetupPage({super.key});

  @override
  State<NetworkManagerSetupPage> createState() =>
      _NetworkManagerSetupPageState();
}

class _NetworkManagerSetupPageState extends State<NetworkManagerSetupPage> {
  DefaultBaseNetworkManager? _networkManager;
  RealApiNetworkService? _networkService;
  AppLogger? _logger;
  IConnectivityManager? _connectivityService;

  late Future<void> _initializationFuture;

  @override
  void initState() {
    super.initState();
    _initializationFuture = _initializeServices();
  }

  Future<void> _initializeServices() async {
    try {
      // Initialize logger service
      _logger = AppLoggerImpl();

      // Initialize connectivity service (async)
      _connectivityService = await ConnectivityManagerFactory.create();

      // Initialize network manager with JSONPlaceholder API
      _networkManager = DefaultBaseNetworkManager(
        _logger!,
        _connectivityService!,
        baseUrl: 'https://jsonplaceholder.typicode.com',
        timeoutSeconds: 30,
      );

      // Initialize network service
      _networkService = RealApiNetworkService(_networkManager!);
    } catch (e) {
      _logger?.error('Failed to initialize services: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Network Manager Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: FutureBuilder<void>(
        future: _initializationFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return _buildLoadingScreen();
          }

          if (snapshot.hasError) {
            return _buildErrorScreen(snapshot.error.toString());
          }

          return _buildMainContent();
        },
      ),
    );
  }

  Widget _buildLoadingScreen() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text(
            'Initializing Network Manager...',
            style: TextStyle(fontSize: 16),
          ),
          SizedBox(height: 8),
          Text(
            'Setting up connectivity and network services',
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorScreen(String error) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Theme.of(context).colorScheme.error,
            ),
            const SizedBox(height: 16),
            Text(
              'Initialization Failed',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                color: Theme.of(context).colorScheme.error,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Failed to initialize network services',
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            Text(
              error,
              style: Theme.of(
                context,
              ).textTheme.bodySmall?.copyWith(color: Colors.grey[600]),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _initializationFuture = _initializeServices();
                });
              },
              child: const Text('Retry Initialization'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMainContent() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(
                        Icons.check_circle,
                        color: Colors.green,
                        size: 20,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        'Network Manager Ready',
                        style: Theme.of(context).textTheme.headlineSmall
                            ?.copyWith(fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  _buildConfigInfo(
                    'Base URL',
                    'https://jsonplaceholder.typicode.com',
                  ),
                  _buildConfigInfo('Timeout', '30 seconds'),
                  _buildConfigInfo('Content Type', 'application/json'),
                  const SizedBox(height: 16),
                  Text(
                    'Active Interceptors:',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Text('• Custom Log Interceptor'),
                  const Text('• Connectivity Interceptor'),
                  const Text('• Background Transformers'),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Available Demonstrations',
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 12),
                  const Text('• GET requests with and without authentication'),
                  const Text('• POST requests with JSON body'),
                  const Text('• PUT requests for updates'),
                  const Text('• DELETE requests'),
                  const Text('• Error handling scenarios'),
                  const Text('• Custom headers management'),
                  const Text('• Query parameters'),
                  const Text('• Network connectivity checking'),
                ],
              ),
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () => _navigateToDemo(),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 16),
              backgroundColor: Theme.of(context).colorScheme.primary,
              foregroundColor: Theme.of(context).colorScheme.onPrimary,
            ),
            child: Text(
              'Start Network Demo',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
                color: Theme.of(context).colorScheme.onPrimary,
              ),
            ),
          ),
          const SizedBox(height: 16),
          OutlinedButton(
            onPressed: () => _showNetworkManagerInfo(),
            child: const Text('View Network Manager Details'),
          ),
        ],
      ),
    );
  }

  Widget _buildConfigInfo(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
          ),
          Expanded(
            child: Text(value, style: TextStyle(color: Colors.grey[700])),
          ),
        ],
      ),
    );
  }

  void _navigateToDemo() {
    if (_networkService != null && _networkManager != null) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => NetworkDemoPage(
            networkService: _networkService!,
            networkManager: _networkManager!,
          ),
        ),
      );
    }
  }

  void _showNetworkManagerInfo() {
    if (_networkManager == null) return;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Network Manager Information'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                'Headers:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              Text(_networkManager!.allHeaders.toString()),
              const SizedBox(height: 16),
              const Text(
                'Interceptors:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              Text('Count: ${_networkManager!.allInterceptors.length}'),
              const SizedBox(height: 8),
              ...(_networkManager!.allInterceptors.map(
                (interceptor) => Text('• ${interceptor.runtimeType}'),
              )),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }
}
0
likes
160
points
80
downloads

Publisher

unverified uploader

Weekly Downloads

A comprehensive Flutter network manager package with authentication, interceptors, and error handling support.

Repository (GitHub)
View/report issues

Topics

#networking #http #authentication #interceptors #error-handling

Documentation

API reference

License

MIT (license)

Dependencies

app_logger_manager, collection, dio, flutter, flutter_connectivity_manager, flutter_shared_utilities

More

Packages that depend on client_network_manager