Webview Asset Loader using InternalStoragePathHandler failing all network calls in the webapp

106 views Asked by At

Has anyone used WebviewAssetLoader in InAppWebview package. I am trying to download my webassets and store it in internal storage using InternalStoragePathHandler. I was able to load the UI but the network calls which is made from the web app inside webview are getting 404 error.But, with same network call if I test it through postman I am getting the response with status code 200. Can anyone help me on this? Please find the output image attached and code below,

// ignore_for_file: prefer_const_declarations
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'package:archive/archive.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import 'package:native_app/widgets/drawer.dart';
import 'package:path_provider/path_provider.dart';

import 'dart:io';

class Sample extends StatefulWidget {
  const Sample({super.key});

  @override
  State<Sample> createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  CookieManager cookieManager = CookieManager.instance();
  ProxyController proxyController = ProxyController.instance();
  InAppWebViewController? _controller;

  final GlobalKey webViewKey = GlobalKey();

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

  InAppWebViewSettings settings = InAppWebViewSettings(
    // allowFileAccessFromFileURLs: true,
    // allowUniversalAccessFromFileURLs: true,
    // allowFileAccess: true,
    // allowContentAccess: true,
    useShouldInterceptAjaxRequest: false,
    useShouldInterceptFetchRequest: false,
    useShouldInterceptRequest: false,
    webViewAssetLoader: WebViewAssetLoader(
      domain: "test.flow.io",
      httpAllowed: true,

      pathHandlers: [
        InternalStoragePathHandler(
          directory:
              '/data/data/com.example.native_app/app_flutter/',
          path: '/',
        ),
      ],
    ),
    javaScriptEnabled: true,
    // safeBrowsingEnabled: true,
  );

  Future<void> downloadAndUnzipFile() async {
    final url =
        'DOWNLOAD_URL';
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      final bytes = response.bodyBytes;

      // Unzip the file
      final archive = ZipDecoder().decodeBytes(bytes);

      // Specify the directory where you want to store the unzipped files
      final directory = await getApplicationDocumentsDirectory();
      // final directory = await getTemporaryDirectory();
      //final directory = await getExternalStorageDirectory();
      final outputDir =
          Directory('${directory?.path}/UIM_19qbevd50qnxvnullC326');
      // Directory('${directory.path}');

      if (!outputDir.existsSync()) {
        outputDir.createSync(recursive: true);
      }
      var i = 0;
      for (final file in archive) {
        final fileName = file.name;
        final filePath = '${outputDir.path}/$fileName';

        if (file.isFile) {
          File outFile = File(filePath);
          final data = file.content as List<int>;
          File(filePath)
            ..createSync(recursive: true)
            ..writeAsBytesSync(data);
          print('print ${i} ${file.name}');
          i++;
          if (file.name == 'page/dist/component/index.html') {
            // print('print1 ${tempFile.path}/${file.name}');
            print('print2 ${outFile.path}');
          }
        }
      }

      print('Files unzipped and stored in: ${outputDir.path}');
    } else {
      throw Exception('Failed to download the file');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Warranty Claim'),
      ),
      drawer: MyDrawer(
        email: "[email protected]",
        name: "Shri Prakash",
      ),
      body: SafeArea(
          child: SingleChildScrollView(
        physics: NeverScrollableScrollPhysics(),
        child: Column(
          children: <Widget>[
            Container(
              height: MediaQuery.of(context).size.height,
              child: InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(
                  url: WebUri("about:blank"),
                ),
                initialSettings: settings,
                onWebViewCreated: (controller) async {
                  _controller = controller;

                  await downloadAndUnzipFile();

                  var box = Hive.box('auth');

                  final cookieValues = {
                    'accessToken': box.get('accessToken') ?? '',
                    'tokenType': box.get('tokenType') ?? '',
                    'issuedAt': box.get('issuedAt') ?? '',
                    'refreshToken': box.get('refreshToken') ?? '',
                  };

                  // set the expiration date for the cookie in milliseconds
                  final expiresDate = DateTime.now()
                      .add(Duration(days: 3))
                      .millisecondsSinceEpoch;

                  final url = WebUri("https://test.flow.io/");

                  cookieValues.forEach((name, value) async {
                    await cookieManager.setCookie(
                      url: url,
                      name: name,
                      value: value.toString(),
                      expiresDate: expiresDate,
                      isSecure: true,
                    );
                  });
                  controller.loadUrl(
                    urlRequest: URLRequest(
                      url: WebUri(
                        'https://test.flow.io/UIM_19qbevd50qnxvnullC326/page/dist/component/index.html'),
                    ),
                  );
                },
              ),
            )
          ],
        ),
      )),
    );
  }
}

0

There are 0 answers