Flutter 是否有可用的Internet连接

2019-06-24  本文已影响0人  LK110

话不多说,直接上代码:

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('点击屏幕,重新加载'),
                    ],
                  ),
                ),
              ),
            );
          }
        },
      ),
    );
  }
}
主要就是这上面的代码
上一篇下一篇

猜你喜欢

热点阅读