【问题标题】:Run Flutter App only if internet connection is available仅在互联网连接可用时运行 Flutter App
【发布时间】:2019-08-28 13:39:29
【问题描述】:

我希望我的 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());}

【问题讨论】:

  • 检查互联网是否在线或离线如果离线显示警报我看到这么多应用程序。

标签: dart flutter


【解决方案1】:

您不能直接在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 ..."),
      ),
    );
  }
}

【讨论】:

  • 未定义名称'上下文'。
  • getter 'isNotEmpty' 没有为类 'Future>'.dart(undefined_getter) 定义
  • 不@CopsOnRoad
  • @richie 好的,原因是您的原始代码不包含 catchError() 我现在添加了它,它是 100% 工作的。
猜你喜欢
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2022-11-07
  • 2022-11-05
  • 1970-01-01
相关资源
最近更新 更多