Connectivity Status in Flutter



Add following plugins in pubspec.yaml file:

connectivity: ^3.0.3

import 'dart:io';

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

void main() {
  runApp(MaterialApp(
    home: MyConnection(),
    title: "Connectivity",
  ));
}

class MyConnection extends StatefulWidget {
  @override
  _MyConnectionState createState() => _MyConnectionState();
}

class _MyConnectionState extends State<MyConnection> {
  String status = "";
  var subs;
  bool isConn = false;
  Connectivity connectivityResult = Connectivity();

  @override
  initState() {
    super.initState();
    subs = connectivityResult.onConnectivityChanged
        .listen((ConnectivityResult result) {
      setState(() {
        if (result == ConnectivityResult.mobile) {
          status = "Mobile Network Used";
          isConn = false;
        } else if (result == ConnectivityResult.wifi) {
          status = "Wifi Network Used";
          isConn = false;
        } else if (result == ConnectivityResult.none) {
          status = "No Internet Used";
          isConn = true;
        }
      });
    });
  }

  @override
  dispose() {
    super.dispose();
    subs.cancel();
  }

  @override
  Widget build(BuildContext context) {
    //checkInternet().then((value) => status = value);

    return Scaffold(
      appBar: AppBar(
        title: Text("Connection State"),
      ),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircleAvatar(
                radius: 100,
                backgroundColor: Colors.redAccent,
                child: CircleAvatar(
                  radius: 95,
                  backgroundColor: (isConn) ? Colors.red : Colors.green,
                  child: (isConn)
                      ? Icon(
                          Icons.wifi_off,
                          size: 100,
                        )
                      : Icon(
                          Icons.wifi,
                          size: 100,
                        ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Text(
                "$status",
                style: TextStyle(fontSize: 30),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

No comments: