如果用户没有互联网,我想在WebView应用程序中更改“网页不可用”。
我阅读了文档,然后尝试了另外一些puglins
import 'package:webview_flutter/webview_flutter.dart';
[...]
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: const WebView(
initialUrl: 'https://google.com',
javascriptMode: JavascriptMode.unrestricted,
),
);
}
}
答案 0 :(得分:0)
您可以尝试使用我的插件flutter_inappwebview。在WebView加载URL(onLoadError
事件)以及接收HTTP错误(例如403、404等)(onLoadHttpError
事件)时,它具有管理错误的事件。
带有工作代码的完整示例,如果用户没有互联网连接,该示例将加载自定义错误页面:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: InAppWebViewPage()
);
}
}
class InAppWebViewPage extends StatefulWidget {
@override
_InAppWebViewPageState createState() => new _InAppWebViewPageState();
}
class _InAppWebViewPageState extends State<InAppWebViewPage> {
InAppWebViewController webView;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("InAppWebView")
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: Container(
child: InAppWebView(
initialUrl: "https://flutter.dev/",
initialHeaders: {},
initialOptions: InAppWebViewWidgetOptions(
inAppWebViewOptions: InAppWebViewOptions(
debuggingEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) {
},
onLoadError: (InAppWebViewController controller, String url, int code, String message) async {
print("error $url: $code, $message");
var tRexHtml = await controller.getTRexRunnerHtml();
var tRexCss = await controller.getTRexRunnerCss();
controller.loadData(data: """
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
<style>$tRexCss</style>
</head>
<body>
$tRexHtml
<p>
URL $url failed to load.
</p>
<p>
Error: $code, $message
</p>
</body>
</html>
""");
},
onLoadHttpError: (InAppWebViewController controller, String url, int statusCode, String description) async {
print("HTTP error $url: $statusCode, $description");
},
),
),
),
]))
);
}
}
结果是:
此示例直接加载html源,但是您可以从资产文件夹或url加载html文件。
只是为了好玩:我的插件包含Google Chrome t-rex游戏的javascript和CSS代码!