檢測網路狀態 - flutter

LiErDan發表於2020-12-29
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

class NetWorkDetection extends StatefulWidget {
  @override
  _NetWorkDetectionState createState() => _NetWorkDetectionState();
}

class _NetWorkDetectionState extends State<NetWorkDetection> {

  var _state;

  var _subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile) {
        setState(() {
          _state="手機網路";
        });
// I am connected to a mobile network.
      } else if (result == ConnectivityResult.wifi) {
        setState(() {
          _state="Wifi 網路";
        });
// I am connected to a wifi network.
      }else{
        setState(() {
          _state="沒有網路";
        });
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("檢測網路變化"),
      ),
      body:Text("${_state}"),
    );
  }
}

相關文章