From 6e9f817a9b0bf492dbfab9bf225a41bc7f4409d6 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Fri, 8 Jul 2022 21:51:56 -0500 Subject: [PATCH] Encode/decode JSON when passing data between languages --- lib/src/controller/impl/mobile.dart | 16 +++++++++++++--- lib/src/utils/html_utils.dart | 10 ++++------ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/lib/src/controller/impl/mobile.dart b/lib/src/controller/impl/mobile.dart index d3c2be9..9cd9845 100644 --- a/lib/src/controller/impl/mobile.dart +++ b/lib/src/controller/impl/mobile.dart @@ -1,4 +1,6 @@ import 'dart:async' show Future; +import 'dart:convert'; +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; @@ -127,9 +129,17 @@ class WebViewXController extends ChangeNotifier // (MOBILE ONLY) Unquotes response if necessary // - // In the mobile version responses from Js to Dart come wrapped in single quotes (') - // The web works fine because it is already into it's native environment - return HtmlUtils.unQuoteJsResponseIfNeeded(result); + // The web works fine because it is already into its native environment + // but on mobile we need to parse the result + if (Platform.isAndroid) { + // On Android `result` will be JSON, so we decode it + return json.decode(result); + } else { + /// TODO: make sure this works on iOS + // In the iOS version responses from JS to Dart come wrapped in single quotes (') + // Note that the supported types are more limited because of connector.evaluateJavascript + return HtmlUtils.unQuoteJsResponseIfNeeded(result); + } } /// This function allows you to evaluate 'raw' javascript (e.g: 2+2) diff --git a/lib/src/utils/html_utils.dart b/lib/src/utils/html_utils.dart index 56173a6..edd7ccd 100644 --- a/lib/src/utils/html_utils.dart +++ b/lib/src/utils/html_utils.dart @@ -134,7 +134,10 @@ class HtmlUtils { } for (final param in params) { - args.write(addSingleQuotes(param.toString())); + // Encode JSON from param + // For example, strings will be encoded so JavaScript reads them exactly + // as on Dart + args.write(json.encode(param)); args.write(','); } @@ -144,11 +147,6 @@ class HtmlUtils { return function; } - /// Adds single quotes to the param - static String addSingleQuotes(String data) { - return "'$data'"; - } - /// Embeds js in the HTML source at the specified position /// This is just a helper function for the generic [embedInHtmlSource] function static String embedJsInHtmlSource(