Handle connectivity in flutter. in a minute

您所在的位置:网站首页 声音科学小实验教案设计思路 Handle connectivity in flutter. in a minute

Handle connectivity in flutter. in a minute

2023-11-09 11:15| 来源: 网络整理| 查看: 265

Handle connectivity in flutterMd Sadab WasimINDIAN CODER

Md Sadab Wasim

·

Follow

Published in

INDIAN CODER

·2 min read·Nov 11, 2018

--

in a minute

“connection” by rawpixel on Unsplash

In some apps, we need the user to be connected with the internet, so that we can do our background work flawlessly. In this article, we are going to learn how can we check that, whether our app is connected to the internet or not without using connectivity plugin. Why?

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet.

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

Let’s create a method that returns a Future and let us know whether the user is online or offline.

//Use dart.io for lookup method.import 'dart:io';Future _checkConnectivity() async {bool connect;try {final result = await InternetAddress.lookup('google.com');if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {connect = true;}} on SocketException catch (_) {connect = false;}return connect;}

Here we are just checking a website response ( google.com) if it is successful which means our app is connected to the internet.

Now you can use this method anywhere in your app to verify that your app is online or not. Here’s an example

@overrideWidget build(BuildContext context) {bool connected;_checkConnectivity().then((internet) {setState(() {connected = internet;});});return new Scaffold(body: connected ? OnlineWork() : OfflineWork(););}

That’s it, folks I hope you guys learn something new.

check out my other articles on flutter.

Don’t forget to hit the clap button 👏 👏



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3