Skip to content

heartsradiant/network_type_reachability

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Network_type_reachability

This library is based on and inspired by the library "flutter_reachability"

This library uses the following dependencies

permission_handler: 9.2.0
dart_ping:
dart_ping_ios:

Next, the necessary configurations for the correct operation of "Network_type_reachability" will be shown, but it is recommended to take a look at the original packages.


Permission_handler settings

Android

Upgrade pre 1.12 Android projects

Since version 4.4.0 this plugin is implemented using the Flutter 1.12 Android plugin APIs. Unfortunately this means App developers also need to migrate their Apps to support the new Android infrastructure. You can do so by following the Upgrading pre 1.12 Android projects migration guide. Failing to do so might result in unexpected behaviour. Most common known error is the permission_handler not returning after calling the .request() method on a permission.

AndroidX

As of version 3.1.0 the permission_handler plugin switched to the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project is also upgraded to support AndroidX. Detailed instructions can be found here.

The TL;DR version is:

  1. Add the following to your "gradle.properties" file:

    android.useAndroidX=true android.enableJetifier=true

copied to clipboard

  1. Make sure you set the compileSdkVersion in your "android/app/build.gradle" file to 31:

    android { compileSdkVersion 31 ... }

copied to clipboard

  1. Make sure you replace all the android. dependencies to their AndroidX counterparts (a full list can be found here).

Add permissions to your AndroidManifest.xml file. There's a debug, main and profile version which are chosen depending on how you start your app. In general, it's sufficient to add permission only to the main version. Here's an example AndroidManifest.xml with a complete list of all possible permissions.

Ios

Add permission to your Info.plist file. Here's an example Info.plist with a complete list of all possible permissions.

IMPORTANT: You will have to include all permission options when you want to submit your App. This is because the permission_handler plugin touches all different SDKs and because the static code analyser (run by Apple upon App submission) detects this and will assert if it cannot find a matching permission option in the Info.plist. More information about this can be found here.

The permission_handler plugin use macros to control whether a permission is enabled.

You must list permission you want to use in your application :

  1. Add the following to your Podfile file:

    post_install do |installer|
      installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
          ... # Here are some configurations automatically generated by flutter
    
          # You can enable the permissions needed here. For example to enable camera
          # permission, just remove the `#` character in front so it looks like this:
          #
          # ## dart: PermissionGroup.camera
          # 'PERMISSION_CAMERA=1'
          #
          #  Preprocessor definitions can be found in: https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
            '$(inherited)',
    
            ## dart: PermissionGroup.calendar
            # 'PERMISSION_EVENTS=1',
    
            ## dart: PermissionGroup.reminders
            # 'PERMISSION_REMINDERS=1',
    
            ## dart: PermissionGroup.contacts
            # 'PERMISSION_CONTACTS=1',
    
            ## dart: PermissionGroup.camera
            # 'PERMISSION_CAMERA=1',
    
            ## dart: PermissionGroup.microphone
            # 'PERMISSION_MICROPHONE=1',
    
            ## dart: PermissionGroup.speech
            # 'PERMISSION_SPEECH_RECOGNIZER=1',
    
            ## dart: PermissionGroup.photos
            # 'PERMISSION_PHOTOS=1',
    
            ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
            # 'PERMISSION_LOCATION=1',
    
            ## dart: PermissionGroup.notification
            # 'PERMISSION_NOTIFICATIONS=1',
    
            ## dart: PermissionGroup.mediaLibrary
            # 'PERMISSION_MEDIA_LIBRARY=1',
    
            ## dart: PermissionGroup.sensors
            # 'PERMISSION_SENSORS=1',   
    
            ## dart: PermissionGroup.bluetooth
            # 'PERMISSION_BLUETOOTH=1',
    
            ## dart: PermissionGroup.appTrackingTransparency
            # 'PERMISSION_APP_TRACKING_TRANSPARENCY=1',
    
            ## dart: PermissionGroup.criticalAlerts
            # 'PERMISSION_CRITICAL_ALERTS=1'
          ]
    
        end
      end
    end
    

    copied to clipboard

  2. Remove the # character in front of the permission you do want to use. For example if you need access to the calendar make sure the code looks like this:

            ## dart: PermissionGroup.calendar
            'PERMISSION_EVENTS=1',
    

    copied to clipboard

  3. Delete the corresponding permission description in Info.plist e.g. when you don't need camera permission, just delete 'NSCameraUsageDescription' The following lists the relationship between Permission and The key of Info.plist:

    Permission

    Info.plist

    Macro

    PermissionGroup.calendar

    NSCalendarsUsageDescription

    PERMISSION_EVENTS

    PermissionGroup.reminders

    NSRemindersUsageDescription

    PERMISSION_REMINDERS

    PermissionGroup.contacts

    NSContactsUsageDescription

    PERMISSION_CONTACTS

    PermissionGroup.camera

    NSCameraUsageDescription

    PERMISSION_CAMERA

    PermissionGroup.microphone

    NSMicrophoneUsageDescription

    PERMISSION_MICROPHONE

    PermissionGroup.speech

    NSSpeechRecognitionUsageDescription

    PERMISSION_SPEECH_RECOGNIZER

    PermissionGroup.photos

    NSPhotoLibraryUsageDescription

    PERMISSION_PHOTOS

    PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse

    NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription

    PERMISSION_LOCATION

    PermissionGroup.notification

    PermissionGroupNotification

    PERMISSION_NOTIFICATIONS

    PermissionGroup.mediaLibrary

    NSAppleMusicUsageDescription, kTCCServiceMediaLibrary

    PERMISSION_MEDIA_LIBRARY

    PermissionGroup.sensors

    NSMotionUsageDescription

    PERMISSION_SENSORS

    PermissionGroup.bluetooth

    NSBluetoothAlwaysUsageDescription, NSBluetoothPeripheralUsageDescription

    PERMISSION_BLUETOOTH

    PermissionGroup.appTrackingTransparency

    NSUserTrackingUsageDescription

    PERMISSION_APP_TRACKING_TRANSPARENCY

    PermissionGroup.criticalAlerts

    PermissionGroupCriticalAlerts

    PERMISSION_CRITICAL_ALERTS

  4. Clean & Rebuild


This plugin is suitable for iOS and Android. This plugin allows Flutter apps to detect network changes. You can know the detailed mobile network types, such as 2G, 3G, 4G, 5G. This plugin also allows you to see the status of internet connection

Use

Example

alt text

  1. get NETWORK_TYPE ** Note: Android must dynamically obtain the READ_PHONE_STATE permission to judge 2G/3G/4G/5G**
  String _networkTypeStatic = 'Unknown';

  //widget
  Column(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: [
      const Text('NETWORK_TYPE : '),
      Text(
        _networkTypeStatic,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      TextButton(
        onPressed: () {
          _getCurrentNetworkStatus();
        },
        child: const Text('Get-Data'),
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(
              const Color.fromARGB(255, 162, 229, 188)),
        ),
      )
    ],
  ),

  //function

  _getCurrentNetworkStatus() async {
    if (Platform.isAndroid) {
      await NetworkTypeReachability().getPermisionsAndroid;
    }
    NetworkStatus status =
        await NetworkTypeReachability().currentNetworkStatus();
    switch (status) {
      case NetworkStatus.unreachable:
      //unreachable
      case NetworkStatus.wifi:
      //wifi
      case NetworkStatus.mobile2G:
      //2g
      case NetworkStatus.mobile3G:
      //3g
      case NetworkStatus.mobile4G:
      //4g
      case NetworkStatus.mobile5G:
      //5h
      case NetworkStatus.othermobile:
      //other
    }
    setState(() {
      _networkTypeStatic = status.toString();
    });
  }
    
  1. You can also listen for NETWORK_TYPE changes by subscribing to the stream exposed by Network_type_reachability plugin
  String _networkTypeSuscription = 'Unknown';
  StreamSubscription<NetworkStatus> subscriptionNetworkType;

  @override
  void initState() {
    super.initState();
    _listenNetworkStatus();
  }

  @override
  void dispose() {
    super.dispose();
    subscriptionNetworkType.cancel();
  }

  _listenNetworkStatus() async {
    if (Platform.isAndroid) {
      await NetworkTypeReachability().getPermisionsAndroid;
    }
    subscriptionNetworkType =
        NetworkTypeReachability().onNetworkStateChanged.listen((event) {
      setState(() {
        _networkTypeSuscription = "$event";
      });
    });
  }


  // Widget
  Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      const Text('NETWORK_TYPE Suscription: '),
      Text(
        _networkTypeSuscription,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
    ],
  ),
  1. get Status Internet Conection
  String connectivityInternetStatic = 'Unknown';

  // Widget
  Column(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: [
      const Text('Status Internet Conection : '),
      Text(
        connectivityInternetStatic,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      TextButton(
        onPressed: () async {
          print('#=======> cargando');
          connectivityInternetStatic = 'loading...';
          setState(() {});
          InternetStatusConnection data =
              await NetworkTypeReachability()
                  .getInternetStatusConnection();
          print(data);
          print('#=======> finalizando');

          connectivityInternetStatic = data.toString();
          setState(() {});
        },
        child: const Text('Get-Data'),
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(
              const Color.fromARGB(255, 162, 229, 188)),
        ),
      )
    ],
  ),
    
  1. get Status Internet Conection Suscription NOTE: It is recommended not to keep the listening state constantly since behind what it does is load the google.com page and this would constantly consume many megabytes of internet over time
  String connectivityInternetSuscription = 'Unknown';
  StreamSubscription<InternetStatusConnection> subscriptionInternetConnection;

  @override
  void initState() {
    super.initState();
    _listenInternetConnection();
  }

  @override
  void dispose() {
    super.dispose();
    subscriptionInternetConnection.cancel();
    NetworkTypeReachability().listenInternetConnection = false;
  }


  // Widget
  Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      const Text('Status Internet Conection : '),
      Text(
        connectivityInternetSuscription,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
    ],
  )

Getting Started

This project is a starting point for a Flutter plug-in package, a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Releases

No releases published

Packages

No packages published

Languages

  • Dart 48.3%
  • Kotlin 23.2%
  • Swift 17.7%
  • Ruby 7.9%
  • Objective-C 2.9%