📜  如何在Flutter中检查 Internet 连接?

📅  最后修改于: 2022-05-13 01:55:24.150000             🧑  作者: Mango

如何在Flutter中检查 Internet 连接?

在许多应用程序中,您需要在进入主屏幕之前检查 Internet 连接。如果互联网连接不可用,我们可以通知用户打开互联网连接。下面给出了一个示例视频,以了解我们将在本文中做什么。

分步实施

创建一个类或有状态小部件MyApp并返回MaterialApp()。在 MaterialApp 的 home 属性中,调用 HomePage() 类。

Dart
import 'package:checkinginternet/home.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State createState() => _MyAppState();
}
  
class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false,
    home: HomePage(),);
  }
}


Dart
import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State createState() => _HomePageState();
}
  
class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}


Dart
bool ActiveConnection = false;
String T = "";
Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }


Dart
@override
void initState() {
   CheckUserConnection();
    super.initState();
 }


Dart
import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State createState() => _HomePageState();
}
  
class _HomePageState extends State {
    bool ActiveConnection = false;
  String T = "";
  Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }
 @override
  void initState() {
   CheckUserConnection();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}


现在创建另一个类Homepage,我们将在其中实现我们的实际逻辑。

Dart

import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State createState() => _HomePageState();
}
  
class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}

在 Homepage 类中,我们有一个Scaffoldbody属性,其中包含Column小部件。该列有一个 Text 和 OutlinedButton 小部件,我们在其中调用函数CheckUserConnection 。现在您必须定义函数CheckUserConnection(),此函数将进行同步,因为检查 Internet 连接需要一些时间。

Dart

bool ActiveConnection = false;
String T = "";
Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }

我们只是使用传递字符串“google.com”调用查找函数。如果结果不为空,我们调用 setstate()函数,并将变量 Active Connection 更改为 true,其他为 false,

Dart

@override
void initState() {
   CheckUserConnection();
    super.initState();
 }

最终代码看起来像,

Dart

import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State createState() => _HomePageState();
}
  
class _HomePageState extends State {
    bool ActiveConnection = false;
  String T = "";
  Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }
 @override
  void initState() {
   CheckUserConnection();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}

输出: