You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter WebView自定义无网络错误页面(隐藏URL)实现方法咨询

Hey there! Let's fix that default error page issue for your Flutter WebView app. The default error message shows the URL which isn't ideal for user experience, but we can easily replace it with a clean, custom error page using the flutter_webview_plugin's built-in state listeners.

Here's the modified version of your code with the custom error handling:

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:covidwho/layout/myAppBar.dart';

class Who extends StatefulWidget {
  @override
  _WhoState createState() => _WhoState();
}

class _WhoState extends State<Who> {
  final FlutterWebviewPlugin _webviewPlugin = FlutterWebviewPlugin();
  bool _isNetworkError = false;

  @override
  void initState() {
    super.initState();
    // Listen for WebView state changes to catch errors
    _webviewPlugin.onStateChanged.listen((WebViewStateChanged state) {
      setState(() {
        if (state.type == WebViewState.error) {
          _isNetworkError = true;
        } else if (state.type == WebViewState.startLoad || state.type == WebViewState.finishLoad) {
          _isNetworkError = false;
        }
      });
    });

    // Optional: Catch HTTP errors like 404/500
    _webviewPlugin.onHttpError.listen((_) {
      setState(() => _isNetworkError = true);
    });
  }

  @override
  void dispose() {
    // Clean up the plugin to avoid memory leaks
    _webviewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(),
      body: _isNetworkError 
          ? _buildCustomErrorPage()
          : Container(
              child: WebviewScaffold(
                url: "https://covid19.who.int/",
                withJavascript: true,
                withLocalStorage: true,
                hidden: true,
                initialChild: Container(
                  color: Colors.white,
                  child: const Center(
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.black,
                    ),
                  ),
                ),
              ),
            ),
    );
  }

  // Your custom error page - tweak this to match your app's style!
  Widget _buildCustomErrorPage() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Icon(
              Icons.wifi_off,
              size: 72,
              color: Colors.grey.shade600,
            ),
            const SizedBox(height: 20),
            const Text(
              "Oops! No Internet Connection",
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              "Please check your network settings and try again.",
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey.shade600,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: () => _webviewPlugin.reload(),
              child: const Text("Try Again"),
            ),
          ],
        ),
      ),
    );
  }
}

Key Changes Explained:

  • We initialized a FlutterWebviewPlugin instance to listen for WebView state changes and errors.
  • In initState, we set up listeners to detect when the WebView hits an error state (like no internet) and toggle a boolean flag (_isNetworkError) to switch to our custom page.
  • The _buildCustomErrorPage method creates a user-friendly error screen with no exposed URL - you can customize the icons, text, and styling to match your app's design.
  • We added a retry button that triggers a WebView reload, so users can easily try connecting again.
  • Don't forget to dispose the plugin in the dispose method to prevent memory leaks!

To test this, just turn off your device's internet connection - you'll see the clean custom error page instead of the default one with the URL.

内容的提问来源于stack exchange,提问作者Olivia Lundy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:27:32