flutter_webview 保存上次加载的网页以供离线访问

问题描述 投票:0回答:1

我正在尝试保存网页以供离线使用。假设,如果用户有互联网连接并访问了该页面。那么它应该保存最后加载的页面以供离线查看。如果用户没有互联网连接并打开页面,则应该显示之前加载的页面。这可能吗?

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

class MyCertificatesScreen extends StatefulWidget {
  static const routeName = '/webview';

  final String url;

  const MyCertificatesScreen({Key? key, required this.url}) : super(key: key);

  @override
  _MyCertificatesScreenState createState() => _MyCertificatesScreenState();
}

class _MyCertificatesScreenState extends State<MyCertificatesScreen> {
  late InAppWebViewController _controller;
  bool isLoading = true;
  final cacheManager = DefaultCacheManager();

  @override
  void initState() {
    super.initState();

    // Initialize connectivity
    Connectivity().onConnectivityChanged.listen((result) {
      if (result == ConnectivityResult.none) {
        // No internet connection, try loading cached HTML file
        _loadCachedHtmlFile();
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    // Load the appropriate content based on connectivity
    _checkConnectivityAndLoadContent();
  }

  // Function to load cached HTML file
  void _loadCachedHtmlFile() async {
    try {
      final fileInfo = await cacheManager.getFileFromCache(widget.url);
      if (fileInfo != null && fileInfo.file != null && await fileInfo.file.exists()) {
        // Cached file exists, load it
        final fileContent = await fileInfo.file.readAsString();
        _controller.loadData(data: fileContent, mimeType: 'text/html');
      } else {
        // No cached file found, show an error message or a default page
        // You can display an error message here or load a default local HTML file
      }
    } catch (e) {
      // Error loading cached file, show an error message or a default page
      // You can display an error message here or load a default local HTML file
    }
  }

  // Function to check connectivity and load content accordingly
  void _checkConnectivityAndLoadContent() async {
    var connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult != ConnectivityResult.none) {
      // Internet connection available, load web page from URL
      if (_controller != null) {
        _controller.loadUrl(urlRequest: URLRequest(url: Uri.parse(widget.url)));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF5F9FA),
      appBar: null, // Set the app bar to null to remove it
      body: Stack(
        children: [
          InAppWebView(
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                javaScriptEnabled: true,
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              _controller = controller;

              // Load the appropriate content based on connectivity
              _checkConnectivityAndLoadContent();
            },
            onLoadStop: (InAppWebViewController controller, Uri? url) {
              setState(() {
                isLoading = false; // Hide the progress indicator
              });
            },
            onLoadError: (InAppWebViewController controller, Uri? url, int code, String message) {
              // Handle web page loading errors here
              print("Webpage error: $message");

              // If loading from cache fails, show an error message or a default page
              // You can display an error message here or load a default local HTML file
            },
          ),
          if (isLoading)
            Center(
              child: CircularProgressIndicator(), // Show the progress indicator
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    cacheManager.dispose();
    super.dispose();
  }
}
flutter dart android-studio webview flutterwebviewplugin
1个回答
0
投票

我看到你正在使用一个

InAppWebViewController
对象。 如果这个对象是here记录的对象,则您有一个 getHtml() → Future 方法,您可以像这样调用它来获取 HTML:

String html = await _controller.getHtml();

这个

html
字符串可以被存储以供以后离线导航。

© www.soinside.com 2019 - 2024. All rights reserved.