flutter检测网络状态

flutter检测网络状态

原来使用的插件connectivity已经停止使用,现在使用的是新版的connectivity_plus
插件地址:https://pub.dev/packages/connectivity_plus

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

class NetWorkPage extends StatefulWidget {
    
    
  NetWorkPage({
    
    Key? key}) : super(key: key);

  @override
  State<NetWorkPage> createState() => _NetWorkPageState();
}

class _NetWorkPageState extends State<NetWorkPage> {
    
    
  var subscription;
  String _state = "";
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
    
    
      if (result == ConnectivityResult.wifi) {
    
    
        setState(() {
    
    
          _state = "处于WiFi";
        });
      } else if (result == ConnectivityResult.mobile) {
    
    
        setState(() {
    
    
          _state = "处于手机网络";
        });
      } else {
    
    
        setState(() {
    
    
          _state = "没有网络";
        });
      }
      // Got a new connectivity status!
    });
  }

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

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("检测网络变化"),
      ),
      body: Center(
        child: Text("${_state}"),
      ),
    );
  }
}

void main() {
    
    
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
    
    
  const MyApp({
    
    Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: NetWorkPage(),
    );
  }
}

请添加图片描述
请添加图片描述

猜你喜欢

转载自blog.csdn.net/m0_46527751/article/details/123214873
今日推荐