flutter - 如果在 Flutter android 中使用 webview 页面时互联网连接丢失,则显示消息“无互联网”
问题描述
bool connectionStatus = true;
Future check() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
connectionStatus = true;
}
} on SocketException catch (_) {
connectionStatus = false;
}
}
class _BackButtonState extends State<BackButton> {
DateTime backbuttonpressedTime;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size(double.infinity, 0),
child: AppBar(
title: Text(""),
backgroundColor: Colors.deepPurple,
),
),
body: FutureBuilder(
future: check(), // a previously-obtained Future or null
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (connectionStatus == true) {
return WillPopScope(
onWillPop: onWillPop,
child: WebviewScaffold(
url: 'https://www.theonlineindia.co.in',
hidden: true,
initialChild: Container(
child: const Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.deepPurple)),
),
),
),
);
} else {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Text('No internet connection !!!',
style: TextStyle(
// your text
fontFamily: 'Aleo',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
fontSize: 25.0,
)),
),
/* RaisedButton(
onPressed: () {
setState(() {});
},
color: Color(0xFF673AB7),
textColor: Colors.white,
child: Text('Refresh'),
), */
// your button beneath text
],
));
}
}),
);
}
Future<bool> onWillPop() async {
DateTime currentTime = DateTime.now();
//ifbackbuttonhasnotbeenpreedOrToasthasbeenclosed
//Statement 1 Or statement2
bool backButton = backbuttonpressedTime == null ||
currentTime.difference(backbuttonpressedTime) > Duration(seconds: 2);
if (backButton) {
backbuttonpressedTime = currentTime;
Fluttertoast.showToast(
msg: "Double tap to exit the app",
backgroundColor: Colors.deepPurple,
textColor: Colors.white);
return false;
}
exit(0);
return true;
}
}
在上面的代码中,我只能在启动应用程序时显示“无互联网”消息。我想在应用程序启动后显示相同的消息,如果在访问 webview 中的网页时互联网连接丢失。
我宁愿通过代码本身而不是寻找任何插件来实现上述目标。插件将是次要选项。
*
解决方案
选项1
定义一个定期检查连接的计时器
const period= const Duration(seconds:5);
new Timer.periodic(period, (Timer t) => check());
选项 2
使用连接插件并在您的应用程序主小部件中定义一个流
StreamSubscription<ConnectivityResult> networkSubscription;
@override
void initState() {
super.initState();
networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
check();
});
checkNetwork(); // Needed for the check on start
}
推荐阅读
- sql - 根据规则对数据集进行分组?
- mysql - 如何检查数据库字段是否包含非中断空间?
- android - 与 ViewPager2 一起使用时出现 PorterDuffXfermode 错误
- java - 在android中设置多个按钮文本
- json - JsonConvert.DeserializeObject 知道类名(字符串)
- amazon-s3 - Ansible aws_s3 模块获取文件位置
- python - Python中矢量化器的网格搜索
- docker - 是否可以在同一个 Cloud Run 服务中部署两个不同的 docker 镜像
- c# - 正则表达式 - 单引号之间的匹配空间
- javascript - React - 深拷贝数组和对象问题