network_info 2.0.0 copy "network_info: ^2.0.0" to clipboard
network_info: ^2.0.0 copied to clipboard

A standalone Flutter package for retrieving network information (public and local IP addresses)

Network Info Package #

A standalone Flutter package for retrieving network information including public and local IP addresses.

โœจ Simple & Clean API!

Features #

  • ๐ŸŒ Get public IP address (visible on the internet)
  • ๐Ÿ  Get local IP address (LAN/Wi-Fi)
  • ๐Ÿ”„ Multiple fallback services for reliability
  • โšก Auto-initialization - No manual DI setup required
  • ๐ŸŽฏ Simple unified API - One-line access to all features
  • ๐Ÿงช Fully tested with 100+ test cases
  • ๐Ÿ—๏ธ Clean Architecture with SOLID principles
  • ๐Ÿ’‰ Dependency injection support with GetIt
  • ๐ŸŽฏ Type-safe with strong typing
  • ๐Ÿ“ฆ Zero dependencies on other custom packages

Installation #

Add to your pubspec.yaml:

dependencies:
  network_info:
    path: packages/network_info

The simplest way to use this package:

import 'package:network_info/network_info.dart';

// No initialization needed! Auto-initializes on first use

// Get public IP
final publicIp = await NetworkInfo.getPublicIp();
print('Public IP: $publicIp');

// Get local IP
final localIp = await NetworkInfo.getLocalIp();
print('Local IP: $localIp');

// Check connectivity
final isConnected = await NetworkInfo.isConnected();
print('Connected: $isConnected');

// Get all info at once (more efficient)
final info = await NetworkInfo.getNetworkInfo();
print('Public: ${info.publicIp}, Local: ${info.localIp}, Connected: ${info.isConnected}');

With Custom Configuration (Optional) #

import 'package:network_info/network_info.dart';

void main() {
  // Optional: customize before first use
  NetworkInfo.initialize(
    config: NetworkInfoConfig(
      timeout: Duration(seconds: 10),
      retryCount: 5,
    ),
  );
  
  runApp(MyApp());
}

Advanced Usage (Direct DI Access) #

For advanced scenarios, you can still access the repository directly:

1. Setup Dependency Injection #

import 'package:network_info/network_info.dart';

void main() {
  // Initialize the package
  NetworkInfoDI.setupNetworkInfoDI();
  
  runApp(MyApp());
}

2. Use Repository Interface #

import 'package:get_it/get_it.dart';
import 'package:network_info/network_info.dart';

final locator = GetIt.instance;

Future<void> getNetworkInfo() async {
  final networkInfo = locator<INetworkInfoRepository>();
  
  // Get public IP
  final publicIp = await networkInfo.getPublicIp();
  print('Public IP: $publicIp');
  
  // Get local IP
  final localIp = await networkInfo.getLocalIp();
  print('Local IP: $localIp');
  
  // Get network info model
  final info = await networkInfo.getNetworkInfo();
  print('Public: ${info.publicIp}, Local: ${info.localIp}');
}

Architecture #

This package follows Clean Architecture and SOLID principles with clear separation of concerns:

lib/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ domain/              # Business logic layer (pure Dart)
โ”‚   โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ network_info_model.dart
โ”‚   โ”‚   โ”œโ”€โ”€ repository/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ i_network_info_repository.dart
โ”‚   โ”‚   โ””โ”€โ”€ exceptions/
โ”‚   โ”‚       โ””โ”€โ”€ network_info_exception.dart
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ data/                # Data layer (implementation)
โ”‚   โ”‚   โ”œโ”€โ”€ config/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ network_info_config.dart
โ”‚   โ”‚   โ”œโ”€โ”€ data_sources/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ public_ip_data_source.dart
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ local_ip_data_source.dart
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ connectivity_data_source.dart
โ”‚   โ”‚   โ””โ”€โ”€ repository/
โ”‚   โ”‚       โ””โ”€โ”€ network_info_repository_impl.dart
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ di/                  # Dependency injection
โ”‚       โ””โ”€โ”€ network_info_di.dart
โ”‚
โ””โ”€โ”€ network_info.dart        # Public API

SOLID Principles Applied #

  • Single Responsibility: Each class has one clear responsibility
  • Open/Closed: Easy to extend without modifying existing code
  • Liskov Substitution: All implementations can be substituted with their interfaces
  • Interface Segregation: Focused interfaces with only necessary methods
  • Dependency Inversion: High-level modules depend on abstractions

Design Patterns Used #

  • Facade Pattern: Simplified interface hiding system complexity (NetworkInfo)
  • Repository Pattern: Abstracts data source details
  • Dependency Injection: For better testability and flexibility
  • Strategy Pattern: Multiple implementations for different scenarios
  • Singleton Pattern: Single instance management via GetIt

Why Use This Package? #

This package provides a simplified interface to network information. Benefits include:

  • โœ… Simpler API: One line of code instead of multiple DI setup steps
  • โœ… Auto-initialization: No manual setup required
  • โœ… Less boilerplate: No need to manage GetIt or repository instances
  • โœ… Clearer intent: NetworkInfo.getPublicIp() is self-documenting
  • โœ… Backward compatible: Advanced users can still access lower-level APIs
  • โœ… Better DX: Improved developer experience and faster onboarding

Before (v1.x):

NetworkInfoDI.setupNetworkInfoDI();
final repo = GetIt.instance<INetworkInfoRepository>();
final ip = await repo.getPublicIp();

After (v2.x):

final ip = await NetworkInfo.getPublicIp();

Comparison with Other Packages #

Feature This Package network_info_plus connectivity_plus
Simple unified API โœ… โŒ โŒ
Auto-initialization โœ… โŒ โŒ
Public IP โœ… Multiple services โŒ โŒ
Local IP โœ… โœ… โŒ
Connectivity โœ… โŒ โœ…
Clean Architecture โœ… โŒ โŒ
DI Support โœ… GetIt โŒ โŒ
Testability โœ… Full mocking โš ๏ธ Limited โš ๏ธ Limited
SOLID Principles โœ… โŒ โŒ
Retry Logic โœ… Configurable โŒ โŒ
Fallback Services โœ… Multiple โŒ โŒ

Future Enhancements #

  • IPv6 Support: Add IPv6 address retrieval
  • Caching: Add configurable caching for public IP
  • Network Speed: Add network speed testing
  • VPN Detection: Detect if VPN is active
  • Proxy Detection: Detect proxy usage
  • Network Type: Detailed network type (2G/3G/4G/5G)

More Examples #

Custom Configuration #

// Initialize with custom configuration
NetworkInfo.initialize(
  config: NetworkInfoConfig(
    publicIpServices: [
      'https://api.ipify.org?format=text',
      'https://icanhazip.com',
    ],
    timeout: Duration(seconds: 10),
    retryCount: 5,
  ),
);

// Then use normally
final publicIp = await NetworkInfo.getPublicIp();

Custom HTTP Client (Advanced DI) #

import 'package:http/http.dart' as http;

NetworkInfoDI.setupNetworkInfoDI(
  customHttpClient: http.Client(),
  config: NetworkInfoConfig(
    timeout: Duration(seconds: 10),
  ),
);

Error Handling #

Errors are handled gracefully by returning null or false:

// Returns null if offline or service unavailable
final publicIp = await NetworkInfo.getPublicIp();
if (publicIp == null) {
  print('Unable to retrieve public IP (offline or service unavailable)');
} else {
  print('Public IP: $publicIp');
}

// Returns false if offline
final isConnected = await NetworkInfo.isConnected();
if (!isConnected) {
  print('Device is offline');
}

// Always returns a valid model (with null IPs if unavailable)
final info = await NetworkInfo.getNetworkInfo();
print('Connected: ${info.isConnected}');
if (info.hasAnyIp) {
  print('Best IP: ${info.bestAvailableIp}');
}

Testing #

The package includes comprehensive tests:

# Run all tests
cd packages/network_info
flutter test

# Run with coverage
flutter test --coverage

# Generate mocks
dart run build_runner build

SOLID Principles #

  • Single Responsibility: Each class has one clear purpose
  • Open/Closed: Extensible through interfaces
  • Liskov Substitution: All implementations are substitutable
  • Interface Segregation: Small, focused interfaces
  • Dependency Inversion: Depends on abstractions, not concretions

Author #

Sepehr Tabeian

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Copyright (c) 2025 Sepehr Tabeian

0
likes
140
points
185
downloads

Publisher

unverified uploader

Weekly Downloads

A standalone Flutter package for retrieving network information (public and local IP addresses)

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

connectivity_plus, flutter, get_it, http

More

Packages that depend on network_info