flutter_inappwebview to save webpage for offline access if there has no internet

222 Views Asked by At

I'm trying to implement **flutter_cache_manager **to save the loaded webpage in local storage. and when i don't have internet connection and try to access the page, it should have to load the saved webpage. but my code is not working. while i'm on offline and trying to load the saved file, it's not loading the saved file, only showing Webpage not available notice with net::ERR_INTERNET_DISCONNECTED

here is my code of my_certificates_screen.dart

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> {
  InAppWebViewController? _controller;
  bool isLoading = true;
  final cacheManager = DefaultCacheManager();
  bool isOnline = true;
  bool errorOccurred = false;

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

    // Initialize connectivity
    Connectivity().onConnectivityChanged.listen((result) {
      setState(() {
        isOnline = result != ConnectivityResult.none;
      });

      // If connectivity changes and we are offline, attempt to load the cached HTML file
      if (!isOnline) {
        _loadCachedHtmlFile();
      } else if (errorOccurred) {
        // If we had an error previously, try loading the web page again
        _loadWebPageFromUrl();
      }
    });
  }

  // Function to load cached HTML file
  Future<void> _loadCachedHtmlFile() async {
    try {
      final fileInfo = await cacheManager.getFileFromCache(widget.url);
      if (fileInfo != null && fileInfo.file != null && await fileInfo.file.exists()) {
        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
        print("Cached HTML file not found");
      }
    } 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
      print("Error loading cached file: $e");
    }
  }

  // Function to load web page from the URL
  void _loadWebPageFromUrl() {
    if (_controller != null) {
      _controller!.loadUrl(
        urlRequest: URLRequest(
          url: Uri.parse(widget.url),
          headers: {'Cache-Control': 'no-cache'},
        ),
      ).then((_) {
        setState(() {
          isLoading = false;
          errorOccurred = false;
        });
      }).catchError((error) {
        // Handle web page loading error
        print("Webpage loading error: $error");
        setState(() {
          errorOccurred = true;
        });
      });
    }
  }

  @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: (controller) {
              // Capture the controller when it's created
              _controller = controller;

              // Load the appropriate content based on connectivity
              _checkConnectivityAndLoadContent();
            },
            onLoadStop: (controller, url) {
              setState(() {
                isLoading = false;
              });
            },
            onLoadError: (controller, url, code, message) {
              // Handle web page loading errors
              print("Webpage error: $message");
              setState(() {
                errorOccurred = true;
              });
            },
          ),
          if (isLoading)
            Center(
              child: CircularProgressIndicator(), // Show the progress indicator
            ),
        ],
      ),
    );
  }

  // Function to check connectivity and load content accordingly
  void _checkConnectivityAndLoadContent() {
    if (isOnline) {
      // If online, try loading the web page from the URL
      _loadWebPageFromUrl();
    } else {
      // If offline, attempt to load the cached HTML file
      _loadCachedHtmlFile();
    }
  }

  @override
  void dispose() {
    cacheManager.dispose();
    super.dispose();
  }
}
0

There are 0 best solutions below