in_app_webview_fetch_test.dart 4.69 KB
Newer Older
1 2 3 4
import 'dart:convert';

import 'package:flutter/material.dart';

5
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
6 7 8

import 'main_test.dart';
import 'custom_widget_test.dart';
9
import '.env.dart';
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

class InAppWebViewFetchTest extends WidgetTest {
  final InAppWebViewFetchTestState state = InAppWebViewFetchTestState();

  @override
  InAppWebViewFetchTestState createState() => state;
}

class InAppWebViewFetchTestState extends WidgetTestState {
  String appBarTitle = "InAppWebViewFetchTest";
  int totTests = 2;
  int testsDone = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
26
        key: this.scaffoldKey,
27
        appBar: myAppBar(state: this, title: appBarTitle),
28
        drawer: myDrawer(context: context),
29 30 31 32 33
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                child: Container(
                  child: InAppWebView(
34 35 36 37 38 39 40 41 42 43 44 45
                    initialData: InAppWebViewInitialData(data: """
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>InAppWebViewFetchTest</title>
    </head>
    <body>
        <h1>InAppWebViewFetchTest</h1>
        <script>
46
          window.addEventListener('flutterInAppWebViewPlatformReady', function(event) {
47
            fetch(new Request("http://${environment["NODE_SERVER_IP"]}:8082/test-download-file")).then(function(response) {
48
                window.flutter_inappwebview.callHandler('fetchGet', response.status);
49
            }).catch(function(error) {
50
                window.flutter_inappwebview.callHandler('fetchGet', "ERROR: " + error);
51 52 53 54 55 56 57 58 59 60 61 62 63
            });

            fetch("http://${environment["NODE_SERVER_IP"]}:8082/test-ajax-post", {
                method: 'POST',
                body: JSON.stringify({
                    firstname: 'Foo',
                    lastname: 'Bar'
                }),
                headers: {
                  'Content-Type': 'application/json'
                }
            }).then(function(response) {
                response.json().then(function(value) {
64
					window.flutter_inappwebview.callHandler('fetchPost', value);
65
				}).catch(function(error) {
66
				    window.flutter_inappwebview.callHandler('fetchPost', "ERROR: " + error);
67 68
				});
            }).catch(function(error) {
69
                window.flutter_inappwebview.callHandler('fetchPost', "ERROR: " + error);
70 71 72 73 74 75
            });
          });
        </script>
    </body>
</html>
                    """),
76 77
                    initialHeaders: {},
                    initialOptions: InAppWebViewWidgetOptions(
78
                        crossPlatform: InAppWebViewOptions(
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
                            clearCache: true,
                            debuggingEnabled: true,
                            useShouldInterceptFetchRequest: true,
                        )
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;

                      webView.addJavaScriptHandler(handlerName: "fetchGet", callback: (args) {
                        appBarTitle = (appBarTitle == "InAppWebViewFetchTest") ? args[0].toString() : appBarTitle + " " + args[0].toString();
                        updateCountTest(context: context);
                      });

                      webView.addJavaScriptHandler(handlerName: "fetchPost", callback: (args) {
                        appBarTitle = (appBarTitle == "InAppWebViewFetchTest") ? args[0]["fullname"] : appBarTitle + " " + args[0]["fullname"];
                        updateCountTest(context: context);
                      });
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) {

                    },
                    shouldInterceptFetchRequest: (InAppWebViewController controller, FetchRequest fetchRequest) async {
                      if (fetchRequest.url.endsWith("/test-ajax-post")) {
                        fetchRequest.body = utf8.encode("""{
                          "firstname": "Lorenzo",
                          "lastname": "Pichilli"
                        }
                        """);
                      }
                      return fetchRequest;
                    },
                  ),
                ),
              ),
            ])
        )
    );
  }

  void updateCountTest({@required BuildContext context}) {
    testsDone++;
    if (testsDone == totTests) {
      setState(() {  });
    }
  }
}