繁体   English   中英

仅当互联网连接可用时才运行 Flutter App

[英]Run Flutter App only if internet connection is available

我希望我的 flutter 应用程序仅在互联网连接可用时运行。 如果互联网不存在显示一个对话框(互联网不存在)我正在使用连接插件但仍然不满意。

这是我的主要功能

Future main() async {
  try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}
  runApp(MyApp());}

您不能直接在main()方法中使用对话框,因为还没有可用的有效context

这是您正在寻找的基本代码。

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    Timer.run(() {
      try {
        InternetAddress.lookup('google.com').then((result) {
          if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            print('connected');
          } else {
            _showDialog(); // show dialog
          }
        }).catchError((error) {
          _showDialog(); // show dialog
        });
      } on SocketException catch (_) {
        _showDialog();
        print('not connected'); // show dialog
      }
    });
  }

  void _showDialog() {
    // dialog implementation
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Internet needed!"),
            content: Text("You may want to exit the app here"),
            actions: <Widget>[FlatButton(child: Text("EXIT"), onPressed: () {})],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Internet")),
      body: Center(
        child: Text("Working ..."),
      ),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM