仅在有互联网连接时运行Flutter App [英] Run Flutter App only if internet connection is available

查看:83
本文介绍了仅在有互联网连接时运行Flutter App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want my flutter app run only if internet connection is available. If the internet is not present show a dialog(internet is not present) I'm using conectivity plugin but still not satisfied.

此处是我的主要功能

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()方法中使用对话框,因为没有有效的上下文可用。

You can't use dialog in main() method directly because there is no valid context available yet.

这是您要查找的基本代码。

Here is the basic code of what you are looking for.

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 ..."),
      ),
    );
  }
}

这篇关于仅在有互联网连接时运行Flutter App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆