Skip to content

Commit

Permalink
Using webview_flutter instead of flutter_inappwebview to render HTML …
Browse files Browse the repository at this point in the history
…documentation + bumped version to 1.4.1
  • Loading branch information
sveinbjornt committed Aug 13, 2024
1 parent ed10771 commit 0271f45
Showing 9 changed files with 39 additions and 134 deletions.
2 changes: 1 addition & 1 deletion ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
@@ -173,7 +173,7 @@
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastUpgradeCheck = 1510;
LastUpgradeCheck = 1540;
ORGANIZATIONNAME = "";
TargetAttributes = {
97C146ED1CF9000F007C117D = {
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1510"
LastUpgradeVersion = "1540"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
2 changes: 1 addition & 1 deletion lib/info.dart
Original file line number Diff line number Diff line change
@@ -59,7 +59,7 @@ Future<String> getHumanFriendlyVersionString() async {
return "$version ($osName)";
}

/// Return marketing version string, e.g. "1.4.0", "1.3.3 dbg"
/// Return marketing version string, e.g. "1.4.1", "1.3.3 dbg"
Future<String> getMarketingVersion() async {
final packageInfo = await PackageInfo.fromPlatform();
if (kDebugMode == true) {
2 changes: 0 additions & 2 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -34,7 +34,6 @@ import './prefs.dart' show Prefs;
import './session.dart' show SessionRoute;
import './theme.dart' show lightThemeData, darkThemeData;
import './hotword.dart' show HotwordDetector;
import './web.dart' show preloadHTMLDocuments;
// import './util.dart' show readServerAPIKey;

void main() async {
@@ -85,7 +84,6 @@ void main() async {

// Init/preload these to prevent any lag after launching app
await preloadAnimationFrames();
//await preloadHTMLDocuments();
await EmblaSession.prepare();

// Initialize singleton, loading hotword-related assets into memory
3 changes: 2 additions & 1 deletion lib/session.dart
Original file line number Diff line number Diff line change
@@ -196,7 +196,8 @@ class SessionRouteState extends State<SessionRoute> with SingleTickerProviderSta
}

Future<bool> isConnectedToInternet() async {
return (await Connectivity().checkConnectivity() != ConnectivityResult.none);
final List<ConnectivityResult> connectivityResult = await Connectivity().checkConnectivity();
return !connectivityResult.contains(ConnectivityResult.none);
}

// Set text field string (and optionally, an associated image)
125 changes: 22 additions & 103 deletions lib/web.dart
Original file line number Diff line number Diff line change
@@ -18,35 +18,16 @@

// Documentation web views.

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

// import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart' show launchUrl, LaunchMode;
import 'package:webview_flutter/webview_flutter.dart';

import './theme.dart' show standardAppBar;
import './common.dart' show dlog;

const String kDocsDir = 'docs';
const String kLoadingHTMLFilePath = "$kDocsDir/loading.html";
const String kLoadingDarkHTMLFilePath = "$kDocsDir/loading_dark.html";

// late InAppWebViewInitialData loadingHTMLData;
// late InAppWebViewInitialData loadingDarkHTMLData;

// /// Preloads the "loading" HTML documents to prevent any initial
// /// lag when showing loading indicator for documentation pages.
// Future<void> preloadHTMLDocuments() async {
// dlog("Preloading HTML loading documents");
// loadingHTMLData =
// InAppWebViewInitialData(data: await rootBundle.loadString(kLoadingHTMLFilePath));
// loadingHTMLData.baseUrl = Uri.parse("file:///");
// loadingDarkHTMLData =
// InAppWebViewInitialData(data: await rootBundle.loadString(kLoadingDarkHTMLFilePath));
// loadingDarkHTMLData.baseUrl = Uri.parse("file:///");
// }

/// Standard web view route used for displaying HTML documentation files.
class WebViewRoute extends StatefulWidget {
final String initialURL;
@@ -58,96 +39,34 @@ class WebViewRoute extends StatefulWidget {
}

class WebViewRouteState extends State<WebViewRoute> {
/// Path to local asset with same filename as remote HTML document.
String _fallbackAssetForURL(String url) {
final Uri uri = Uri.parse(url);
return "$kDocsDir/${uri.pathSegments.last}";
}

/// Add dark=1 query parameter to URL.
/// This param is used to style the HTML document for dark mode via JS.
String _darkURLForURL(String url) {
return "$url?dark=1";
}

// /// Fall back to local HTML document if error comes
// /// up when fetching document from remote server.
// void errHandler(InAppWebViewController controller, Uri? url, int errCode, String desc) async {
// dlog("Page load error for $url: $errCode, $desc");
// final String path = _fallbackAssetForURL(url.toString());
// dlog("Falling back to local asset $path");
// setState(() {
// controller.loadFile(assetFilePath: path);
// });
// }

// /// Handle clicks on links in HTML documentation.
// /// These links should be opened in an external browser to
// /// avoid screwing with the navigation stack of the app.
// Future<NavigationActionPolicy> urlClickHandler(
// InAppWebViewController controller, NavigationAction action) async {
// final URLRequest req = action.request;
// final String urlStr = req.url.toString();
// final String fallbackFilename = _fallbackAssetForURL(urlStr);

// if (urlStr.startsWith(widget.initialURL) == false &&
// urlStr.endsWith(fallbackFilename) == false) {
// // It's not a local URL, so open it in an external browser
// dlog("Opening external URL: ${req.url}");
// await launchUrl(req.url!, mode: LaunchMode.externalApplication);
// return NavigationActionPolicy.CANCEL;
// }

// return NavigationActionPolicy.ALLOW;
// }

// /// Create web view that initially presents a "loading" document with
// /// a progress indicator. Then immediately fetch the actual remote document.
// /// Falls back to loading a local bundled HTML document with the same name
// /// on network error. This ensures that at least *some* version of the
// /// document can be viewed even when the device is offline.
// InAppWebView _buildWebView(BuildContext context) {
// final darkMode = (MediaQuery.platformBrightnessOf(context) == Brightness.dark);
// final loadingURL = darkMode ? kLoadingDarkHTMLFilePath : kLoadingHTMLFilePath;
// final finalURL = darkMode ? _darkURLForURL(widget.initialURL) : widget.initialURL;
// final initialData = darkMode ? loadingDarkHTMLData : loadingHTMLData;

// final webViewOpts = InAppWebViewGroupOptions(
// crossPlatform: InAppWebViewOptions(
// clearCache: kDebugMode,
// useShouldOverrideUrlLoading: true,
// transparentBackground: true,
// ));

// // Create and configure web view
// return InAppWebView(
// initialData: initialData,
// initialUrlRequest: URLRequest(url: Uri.parse(finalURL)),
// initialOptions: webViewOpts,
// onLoadStart: (InAppWebViewController controller, Uri? uri) {
// dlog("Loading URL ${uri.toString()}");
// },
// onLoadStop: (InAppWebViewController controller, Uri? uri) async {
// final String urlStr = uri.toString();
// if (urlStr.endsWith(loadingURL) || urlStr == 'about:blank' || urlStr == 'file:///') {
// // Loading of initial "loading" document is complete.
// // Now load the actual remote document.
// setState(() {
// controller.loadUrl(urlRequest: URLRequest(url: Uri.parse(finalURL)));
// });
// }
// },
// onLoadError: errHandler,
// onLoadHttpError: errHandler,
// shouldOverrideUrlLoading: urlClickHandler,
// onConsoleMessage: (InAppWebViewController controller, ConsoleMessage msg) {
// dlog("Web View Console message: ${msg.message}");
// });
// }

@override
Widget build(BuildContext context) {
return Scaffold(appBar: standardAppBar, body: standardAppBar //buildWebView(context),
);
final darkMode = (MediaQuery.platformBrightnessOf(context) == Brightness.dark);
final finalURL = darkMode ? _darkURLForURL(widget.initialURL) : widget.initialURL;

var controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onHttpError: (HttpResponseError error) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(finalURL));

return Scaffold(appBar: standardAppBar, body: WebViewWidget(controller: controller));
}
}
4 changes: 2 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: embla
description: Cross-platform mobile Icelandic-language voice assistant.
publish_to: 'none'
version: 1.4.1+0
version: 1.4.1+1
homepage: https://embla.is
repository: https://github.com/mideind/EmblaFlutterApp

@@ -24,7 +24,7 @@ dependencies:
url: https://github.com/tommysolsen/platform_device_id.git
path: platform_device_id
connectivity_plus: '>=5.0.2'
# flutter_inappwebview: '^6.0.0'
webview_flutter: ^4.8.0
path_provider: '^2.1.4'
wakelock_plus: '^1.2.7'
permission_handler: ^11.3.1
20 changes: 10 additions & 10 deletions test/classes_test.dart
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ import 'package:flutter/material.dart';

import 'package:embla/animations.dart';
import 'package:embla/hotword.dart';
import 'package:embla/jsexec.dart';
// import 'package:embla/jsexec.dart';
import 'package:embla/loc.dart';
import 'package:embla/prefs.dart';

@@ -14,7 +14,7 @@ void main() {

testAnimations();
testHotword();
testJSExec();
//testJSExec();
testLocationTracker();
testPrefs();
}
@@ -36,15 +36,15 @@ void testHotword() async {
}

// jsexec.dart
void testJSExec() async {
test("JSExecutor should be singleton", () {
expect(JSExecutor() == JSExecutor(), true);
});
// test("JSExecutor should run JavaScript code without issue", () async {
// JSExecutor executor = JSExecutor();
// expect(await executor.run("2+2"), 4);
// void testJSExec() async {
// test("JSExecutor should be singleton", () {
// expect(JSExecutor() == JSExecutor(), true);
// });
}
// // test("JSExecutor should run JavaScript code without issue", () async {
// // JSExecutor executor = JSExecutor();
// // expect(await executor.run("2+2"), 4);
// // });
// }

// loc.dart
void testLocationTracker() async {
13 changes: 0 additions & 13 deletions test/widget_test.dart
Original file line number Diff line number Diff line change
@@ -9,8 +9,6 @@ import 'package:embla/menu.dart';
import 'package:embla/settings.dart';
import 'package:embla/info.dart';
import 'package:embla/voices.dart';
import 'package:embla/web.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() {
// main.dart
@@ -75,15 +73,4 @@ void main() {
expect(find.byType(ListView), findsOneWidget);
expect(find.byType(ListTile), findsAtLeastNWidgets(2));
});

// web.dart
testWidgets('WebViewRoute contains InAppWebView', (tester) async {
preloadHTMLDocuments();
await tester.pumpWidget(
const MaterialApp(
home: WebViewRoute(initialURL: "https://mideind.is"),
),
);
expect(find.byType(InAppWebView), findsOneWidget);
});
}

0 comments on commit 0271f45

Please sign in to comment.