Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
8
Indexable
Never
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

class InternetConnectionChecker extends StatefulWidget {
  @override
  _InternetConnectionCheckerState createState() =>
      _InternetConnectionCheckerState();
}

class _InternetConnectionCheckerState extends State<InternetConnectionChecker> {
  StreamSubscription<ConnectivityResult>? connectivitySubscription;
  ConnectivityResult? connectivityResult;
  bool? hasAccess;

  @override
  void initState() {
    super.initState();
    checkInternetAccess();

    // Subscribe to connectivity changes using a stream
    connectivitySubscription =
        Connectivity().onConnectivityChanged.listen((result) {
          setState(() {
            connectivityResult = result;
            checkInternetAccess();
          });
        });
  }

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

  Future<void> checkInternetAccess() async {
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {
      hasAccess = await hasInternetAccess();
    } else {
      hasAccess = false;
    }
    if (hasAccess == false) {
      // Show an alert dialog when there is no internet access
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('No Internet Access'),
            content: Text('You are not connected to the internet.'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  // Retry the internet connectivity check
                  checkInternetAccess();
                },
                child: Text('Retry'),
              ),
            ],
          );
        },
      );
    }
    setState(() {});
  }

  Future<bool> hasInternetAccess() async {
    try {
      final response = await http.get(Uri.parse("https://www.google.com"));
      return response.statusCode == 200;
    } catch (e) {
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Internet Connection Checker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Network Type: ${connectivityResult?.toString() ?? 'Unknown'}',
              style: TextStyle(fontSize: 20.0),
            ),
            Text(
              'Internet Access: ${hasAccess == true ? 'Available' : 'Not Available'}',
              style: TextStyle(fontSize: 20.0),
            ),
          ],
        ),
      ),
    );
  }
}