Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.1 kB
0
Indexable
Never
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';

class InternetConnectionManager {
  static final InternetConnectionManager _instance =
      InternetConnectionManager._internal();
  factory InternetConnectionManager() => _instance;

  late StreamSubscription<InternetStatus> _connectionSubscription;
  late BuildContext _context;
  bool _isDialogShowing = false;

  InternetConnectionManager._internal() {
    _connectionSubscription =
        InternetConnection().onStatusChange.listen((status) {
      if (status == InternetStatus.disconnected && !_isDialogShowing) {
        _showNoInternetDialog();
      }
    });
  }

  void setContext(BuildContext context) {
    _context = context;
  }

  void _showNoInternetDialog() {
    _isDialogShowing = true;
    showDialog(
      barrierDismissible: false,
      context: _context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('No Internet Connection'),
          content:
              const Text('Please check your internet connection and try again.'),
          actions: <Widget>[
            TextButton(
              child: const Text('Retry'),
              onPressed: () {
                Navigator.of(context).pop();
                _retryInternetConnection();
              },
            ),
          ],
        );
      },
    ).then((_) {
      _isDialogShowing = false;
    });
  }

  void _retryInternetConnection() {
    InternetConnection().hasInternetAccess.then((isConnected) {
      if (isConnected) {
        if (_isDialogShowing) {
          Navigator.of(_context).pop();
          _isDialogShowing = false;
        }
      } else {
        _showNoInternetDialog();
      }
    });
  }

  void _dismissDialog() {
    if (_isDialogShowing) {
      Navigator.of(_context).pop();
      _isDialogShowing = false;
    }
  }

  void dispose() {
    _connectionSubscription.cancel();
  }
}
Leave a Comment