对于登陆这里的其他人,我想添加到Günter Zöchbauer的答案,这是我实现一个实用程序的解决方案,以知道是否有互联网,而不管其他任何事情。
免责声明:
我对Dart和Flutter都是新手,所以这可能不是最好的方法,但很想得到反馈。
结合flutter_connectivity和Günter Zöchbauer的连接测试
我的需求
我不希望在需要检查连接的任何地方出现一堆重复的代码,我希望它在发生变化时自动更新组件或其他与连接相关的东西。
ConnectionStatusSingleton
首先我们设置一个Singleton。如果你不熟悉这种模式,网上有很多关于它们的好信息。但要点在于,您希望在应用程序生命周期中创建类的单个实例,并且能够在任何地方使用它。
这个单例连接到flutter_connectivity并监听连接性更改,然后测试网络连接,然后使用StreamController更新任何关心的内容。
它是这样的:
import 'dart:io'; //InternetAddress utility
import 'dart:async'; //For StreamController/Stream
import 'package:connectivity/connectivity.dart';
class ConnectionStatusSingleton {
//This creates the single instance by calling the `_internal` constructor specified below
static final ConnectionStatusSingleton _singleton = new ConnectionStatusSingleton._internal();
ConnectionStatusSingleton._internal();
//This is what's used to retrieve the instance through the app
static ConnectionStatusSingleton getInstance() => _singleton;
//This tracks the current connection status
bool hasConnection = false;
//This is how we'll allow subscribing to connection changes
StreamController connectionChangeController = new StreamController.broadcast();
//flutter_connectivity
final Connectivity _connectivity = Connectivity();
//Hook into flutter_connectivity's Stream to listen for changes
//And check the connection status out of the gate
void initialize() {
_connectivity.onConnectivityChanged.listen(_connectionChange);
checkConnection();
}
Stream get connectionChange => connectionChangeController.stream;
//A clean up method to close our StreamController
// Because this is meant to exist through the entire application life cycle this isn't
// really an issue
void dispose() {
connectionChangeController.close();
}
//flutter_connectivity's listener
void _connectionChange(ConnectivityResult result) {
checkConnection();
}
//The test to actually see if there is a connection
Future<bool> checkConnection() async {
bool previousConnection = hasConnection;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
hasConnection = true;
} else {
hasConnection = false;
}
} on SocketException catch(_) {
hasConnection = false;
}
//The connection status changed send out an update to all listeners
if (previousConnection != hasConnection) {
connectionChangeController.add(hasConnection);
}
return hasConnection;
}
}
使用
初始化
首先,我们必须确保调用了我们单例的initialize。但只有一次。
这部分取决于你,但我在我的应用程序的main():
void main() {
ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
connectionStatus.initialize();
runApp(MyApp());
//Call this if initialization is occuring in a scope that will end during app lifecycle
//connectionStatus.dispose();
}
在Widget或其他地方
import 'dart:async'; //For StreamSubscription
...
class MyWidgetState extends State<MyWidget> {
StreamSubscription _connectionChangeStream;
bool isOffline = false;
@override
initState() {
super.initState();
ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
_connectionChangeStream = connectionStatus.connectionChange.listen(connectionChanged);
}
void connectionChanged(dynamic hasConnection) {
setState(() {
isOffline = !hasConnection;
});
}
@override
Widget build(BuildContext ctxt) {
...
}
}
希望其他人觉得这有用!
示例github repo: https://github.com/dennmat/flutter-connectiontest-example
在模拟器中切换飞行模式以查看结果