flutter - 在 Flutter 中恢复互联网连接时获取数据
问题描述
我正在开发一个从互联网上获取一些数据的应用程序。为了避免互联网连接出现问题,我添加了连接包。
如果应用程序启动时连接了互联网,然后关闭了互联网连接,我可以显示一个带有“无互联网”文本的容器。如果我再次打开互联网,则会显示数据。
实现这一点的代码如下:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
class CheckNetworkPage extends StatefulWidget {
@override
_CheckNetworkPageState createState() => _CheckNetworkPageState();
}
class _CheckNetworkPageState extends State<CheckNetworkPage> {
StreamSubscription<ConnectivityResult> _networkSubscription;
Future<List<Data>> fetchData() async {
// Code to fetch data
}
@override
initState() {
super.initState();
fetchData();
_networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
_connectionStatus = result.toString();
print(_connectionStatus);
if (result == ConnectivityResult.wifi ||
result == ConnectivityResult.mobile ||
result == ConnectivityResult.none) {
print("Result: $result");
setState(() {});
}
});
}
// Cancel subscription after you are done
@override
dispose() {
super.dispose();
_networkSubscription.cancel();
}
@override
Widget build(BuildContext context) {
// More code. I can use the result of _connectionStatus to build my app
}
}
但是,如果应用程序在没有互联网的情况下启动,当我打开它时,数据不会加载,因为它是在initState()
.
之前没有获取数据并打开互联网连接时如何获取数据?
解决方案
您可以将最新获取的数据存储在变量中。
List<Data> fetchedData;
Future<List<Data>> fetchData() async {
// Code to fetch data
// Add this :
fetchedData = ...
}
然后在您的侦听器中,检查此数据是否已定义:
if (result == ConnectivityResult.wifi ||
result == ConnectivityResult.mobile ||
result == ConnectivityResult.none) {
print("Result: $result");
setState(() {});
// Add this :
if (fetchedData == null) fetchData()
}
推荐阅读
- ruby-on-rails-5 - Rails 5 活动记录查询未显示 left_outer_joins 属性
- pytorch - PyTorch:如何检查训练过程中是否有一些权重没有改变?
- javascript - 动态 CSS 网格生成
- python - python 注册表中缺少图形操作
- c++ - C++ 反转输入顺序并将其打印为 Char*
- sql - Data Studio CASE 错误 - THEN/ELSE 参数的类型不兼容:TEXT/NUMBER
- swift - Firebase RTDB 数据未显示在 SwiftUI 列表视图中
- statistics - 匹配具有相似特征的观察
- css - 在 Boostrap 中对齐、居中、定位元素
- create-react-app - npx create-react-app 后纱线启动不起作用