美文网首页
Flutter 是否有可用的Internet连接

Flutter 是否有可用的Internet连接

作者: LK110 | 来源:发表于2019-06-24 18:20 被阅读0次

    话不多说,直接上代码:

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'dart:io';
    import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
    
    class ConnectionPage extends StatefulWidget {
      @override
      _ConnectionPageState createState() => _ConnectionPageState();
    }
    
    class _ConnectionPageState extends State<ConnectionPage> {
      bool connectionStatus = false;
    
      Future check() async {
        try {
          final result = await InternetAddress.lookup('google.com');
          if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            connectionStatus = true;
            print("connected $connectionStatus");
          }
        } on SocketException catch (_) {
          connectionStatus = false;
          print("not connected $connectionStatus");
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Internet Connection'),
          ),
          body: FutureBuilder(
            future: check(),
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              if (connectionStatus == true) {
                /// 如果网络正常连接
                return SafeArea(
                  child: WebviewScaffold(
                    url: "https://www.baidu.com",
                  ),
                );
              } else {
                /// 如果网络连接失败
                return SafeArea(
                  child: Container(
                    alignment: Alignment.center,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          check();
                        });
                      },
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            Icons.wifi,
                            color: Colors.grey[200],
                            size: 80,
                          ),
                          Text('网络出问题了~请您查看网络设置'),
                          Text('点击屏幕,重新加载'),
                        ],
                      ),
                    ),
                  ),
                );
              }
            },
          ),
        );
      }
    }
    
    主要就是这上面的代码
    

    相关文章

      网友评论

          本文标题:Flutter 是否有可用的Internet连接

          本文链接:https://www.haomeiwen.com/subject/lwzoqctx.html