skip to Main Content

I want to check the internet connection before every dio request using the interceptor and connectivity package in Flutter

2

Answers


  1. 1.First you should Install connectivity package into you’r project.you can add it using bellow cammand,

    flutter pub add connectivity_plus
    

    2.Now you should import into you’r workspace. import

    'package:connectivity_plus/connectivity_plus.dart';
    

    you can refer it by using this link.

    3.Set up an interceptor to check the internet connection before each Dio request. Create a class that extends Interceptor from Dio package: look at bellow code segment,

    import 'package:dio/dio.dart';
    import 'package:connectivity/connectivity.dart';
    
    class ConnectivityInterceptor extends Interceptor {
      final Connectivity connectivity;
    
      ConnectivityInterceptor(this.connectivity);
    
      @override
      Future onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
        var connectivityResult = await connectivity.checkConnectivity();
        if (connectivityResult == ConnectivityResult.none) {
          // Handle case when there is no internet connection
          throw DioError(
            requestOptions: options,
            response: Response(
              requestOptions: options,
              statusCode: 503, // You can set your custom status code
              statusMessage: 'No internet connection',
            ),
          );
        }
        return super.onRequest(options, handler);
      }
    }
    

    4.In your main function or where you configure Dio, set up the Dio instance with the interceptor:

    import 'package:flutter/material.dart';
    import 'package:dio/dio.dart';
    import 'package:connectivity/connectivity.dart';
    
    void main() {
      Dio dio = Dio();
      Connectivity connectivity = Connectivity();
      dio.interceptors.add(ConnectivityInterceptor(connectivity));
      
      runApp(MyApp(dio: dio));
    }
    
    class MyApp extends StatelessWidget {
      final Dio dio;
    
      MyApp({required this.dio});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Dio Connectivity Example'),
            ),
            body: Center(
              child: ElevatedButton(
                onPressed: () {
                  makeDioRequest();
                },
                child: Text('Make Dio Request'),
              ),
            ),
          ),
        );
      }
    
      Future<void> makeDioRequest() async {
        try {
          Response response = await dio.get('https://api.example.com/data');
          print('Response: ${response.data}');
          // Handle the response
        } on DioError catch (e) {
          if (e.response != null && e.response!.statusCode == 503) {
            // Handle case when there is no internet connection
            print('No internet connection');
            // Show a dialog or snackbar indicating no internet
          } else {
            // Handle other Dio errors
            print('Dio error: $e');
            // Show a dialog or snackbar with the error
          }
        }
      }
    }
    
    class ConnectivityInterceptor extends Interceptor {
      final Connectivity connectivity;
    
      ConnectivityInterceptor(this.connectivity);
    
      @override
      Future onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
        var connectivityResult = await connectivity.checkConnectivity();
        if (connectivityResult == ConnectivityResult.none) {
          // Handle case when there is no internet connection
          throw DioError(
            requestOptions: options,
            response: Response(
              requestOptions: options,
              statusCode: 503, // You can set your custom status code
              statusMessage: 'No internet connection',
            ),
          );
        }
        return super.onRequest(options, handler);
      }
    }
    

    I use simple app with button, you can give some idea using this guidelines.

    Login or Signup to reply.
  2. I don’t know the purpose why you wanna use the interceptor and connectivity packages(ignore the answer if you have specific purpose using for them), but for simply checking is internet connection is available or not, i use InternetAddress.lookup from dart:io library like below:

    /// [_isInternetAvailable] Checks if the
    /// internet connection is available or not.
    Future<bool> _isInternetAvailable() async {
      try {
        final foo = await InternetAddress.lookup('google.com');
        return foo.isNotEmpty && foo[0].rawAddress.isNotEmpty ? true : false;
      } catch (e) {
        return false;
      }
    } 
     
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search