dart Flutter Webview更改网页不可用

ehxuflar  于 11个月前  发布在  Flutter
关注(0)|答案(3)|浏览(169)

我想改变“网页不可用”,在我的WebView应用程序,如果用户没有互联网。
我读了文档,并尝试一些其他的puglin

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,
      ),
    );
  }
}

字符串

yvt65v4c

yvt65v4c1#

只需将onWebResourceError方法添加到Webview。

WebView(
        onWebResourceError: (WebResourceError webviewerrr) {
            print("Handle your Error Page here");
        },
        initialUrl: "your url"
        javascriptMode: JavascriptMode.unrestricted,
        onPageFinished: (String url) {
            print('Page finished loading:');
        },
    );

字符串

sf6xfgos

sf6xfgos2#

你可以试试我的插件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");
                    },
                  ),
                ),
              ),
            ]))
    );
  }
}

字符串
其结果是:
x1c 0d1x的数据
这个例子直接加载一个html源,但是你也可以从assets文件夹或者url加载一个html文件。
只是为了好玩:我的插件包括谷歌Chrome t-rex游戏的JavaScript和css代码!

xv8emn3q

xv8emn3q3#

如前所述,InAppWebView有很好的支持。上面建议的实现有点过时。这里是更新的实现,它在页面加载错误时将HTML字符串加载到视图中(超时)。这是经过测试的,适用于最新版本的插件和Android 14。
我没有包括任何其他方法处理,但这里是完整的实施工作。

body: Container(
    child: Column(children: <Widget>[
      Expanded(
        child: Container(
          child: InAppWebView(
            initialUrl: "https://flutter.dev/",
            initialHeaders: {},
             initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                transparentBackground: true,
              ),
              android: AndroidInAppWebViewOptions(
                useHybridComposition: true, // makes scrolling smooth on Android
              ),
            ),
            onWebViewCreated: (controller) {
              // do something with the controller if needed
            },
            onLoadStart: (controller, url) {
              // Show loading indicator etc
            },
            onLoadStop: (controller, url) {
              // Hide loading indicator etc
            },
            onLoadHttpError: (controller, url, statusCode, description) {
                print("HTTP error $url: $statusCode, $description");
            },
            onLoadError: (controller, url, code, message) {
              print("error $url: $code, $message");
              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></style>
                    </head>
                    <body>
                      <p style="color: #ef7174; text-align: center; font-size: 14px; font-weight: normal; padding: 5px; background-color: #fce3e3; border-radius: 30px; margin-top: 40% margin-left: auto; margin-right: auto;">
                        Page not found or there is no internet connection.
                      </p>
                    </body>
                  </html>
              """);
            },
          ),
        ),
      ),
  ]))

字符串

相关问题