flutter_network_client 1.0.1 copy "flutter_network_client: ^1.0.1" to clipboard
flutter_network_client: ^1.0.1 copied to clipboard

Advanced HTTP client for Flutter with authentication, retry logic, and clean architecture.

example/main.dart

import 'package:flutter_network_client/flutter_network_client.dart';
import 'package:logger/logger.dart';

final logger = Logger(
  printer: PrettyPrinter(
    methodCount: 0,
    errorMethodCount: 0,
    lineLength: 80,
    colors: true,
    printEmojis: true,
  ),
);

void main() async {
  // Example 1: Basic HTTP requests
  await basicExample();

  // Example 2: Authentication with tokens
  await authenticationExample();

  // Example 3: File upload
  await fileUploadExample();

  // Example 4: Error handling
  await errorHandlingExample();
}

/// Basic HTTP requests without authentication
Future<void> basicExample() async {
  logger.i('=== Basic HTTP Requests ===');

  final client = FlutterNetworkClient(
    baseUrl: 'https://jsonplaceholder.typicode.com',
    enableRequestLogging: true,
    enableResponseLogging: true,
  );

  try {
    // GET request
    final getResponse = await client.get<List<dynamic>>(
      '/posts',
      queryParameters: {'_limit': '3'},
      parser: (data) => data as List<dynamic>,
    );

    if (getResponse.isSuccess) {
      logger.i('✅ GET Success: Retrieved ${getResponse.data?.length} posts');
    }

    // POST request
    final postResponse = await client.post<Map<String, dynamic>>(
      '/posts',
      body: {
        'title': 'Flutter Network Client Example',
        'body': 'This is a test post from Flutter Network Client',
        'userId': 1,
      },
      parser: (data) => data as Map<String, dynamic>,
    );

    if (postResponse.isSuccess) {
      logger.i(
          '✅ POST Success: Created post with ID ${postResponse.data?['id']}');
    }
  } catch (e) {
    logger.e('❌ Error in basic example: $e');
  } finally {
    client.dispose();
  }
}

/// Authentication example with token management
Future<void> authenticationExample() async {
  logger.i('=== Authentication Example ===');

  final client = FlutterNetworkClient.withTokens(
    baseUrl: 'https://httpbin.org',
    enableRequestLogging: true,
    customRefreshHandler: () async {
      // Simulate token refresh
      return 'Bearer example-token-${DateTime.now().millisecondsSinceEpoch}';
    },
  );

  try {
    final response = await client.get<Map<String, dynamic>>(
      '/bearer',
      useToken: true,
      parser: (data) => data as Map<String, dynamic>,
    );

    if (response.isSuccess) {
      logger.i('✅ Authenticated request successful');
      logger.i('Token used: ${response.data?['token']}');
    }
  } catch (e) {
    logger.e('❌ Error in authentication example: $e');
  } finally {
    client.dispose();
  }
}

/// File upload example
Future<void> fileUploadExample() async {
  logger.i('=== File Upload Example ===');

  final client = FlutterNetworkClient(
    baseUrl: 'https://httpbin.org',
    enableRequestLogging: true,
  );

  try {
    // Create a simple text file for upload
    final textFile = MultipartFile.fromString(
      'Hello from Flutter Network Client!',
      field: 'file',
      filename: 'example.txt',
      contentType: 'text/plain',
    );

    final response = await client.uploadFile<Map<String, dynamic>>(
      '/post',
      textFile,
      fields: {
        'description': 'Example file upload',
        'category': 'test',
      },
      parser: (data) => data as Map<String, dynamic>,
    );

    if (response.isSuccess) {
      logger.i('✅ File upload successful');
      final files = response.data?['files'] as Map<String, dynamic>?;
      if (files != null) {
        logger.i('Uploaded file content: ${files['file']}');
      }
    }
  } catch (e) {
    logger.e('❌ Error in file upload example: $e');
  } finally {
    client.dispose();
  }
}

/// Error handling example
Future<void> errorHandlingExample() async {
  logger.i('=== Error Handling Example ===');

  // Example with rethrowExceptions = false (default)
  final client1 = FlutterNetworkClient(
    baseUrl: 'https://httpbin.org',
    rethrowExceptions: false,
  );

  try {
    final response = await client1.get('/status/404');

    if (!response.isSuccess) {
      logger.w('❌ Request failed with status: ${response.statusCode}');
      logger.w('Error message: ${response.error}');
    }
  } catch (e) {
    logger.e('❌ Unexpected exception: $e');
  } finally {
    client1.dispose();
  }

  // Example with rethrowExceptions = true
  final client2 = FlutterNetworkClient(
    baseUrl: 'https://httpbin.org',
    rethrowExceptions: true,
  );

  try {
    await client2.get('/status/404');
  } catch (e) {
    if (e is NotFoundException) {
      logger.i('✅ Caught NotFoundException: ${e.message}');
      logger.i('Status code: ${e.statusCode}');
    } else {
      logger.e('❌ Unexpected exception type: $e');
    }
  } finally {
    client2.dispose();
  }
}

/// Custom response model example
class Post {
  final int id;
  final int userId;
  final String title;
  final String body;

  Post({
    required this.id,
    required this.userId,
    required this.title,
    required this.body,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      userId: json['userId'],
      title: json['title'],
      body: json['body'],
    );
  }

  @override
  String toString() {
    return 'Post{id: $id, title: $title}';
  }
}
1
likes
160
points
39
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Advanced HTTP client for Flutter with authentication, retry logic, and clean architecture.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, http, http_parser, logger, shared_preferences

More

Packages that depend on flutter_network_client