Two-Way Connection on App
This page will introduce how the App in the TownPass open-source project engages in two-way Connection with TownPass.
Connection Mechanism
As mentioned on the Introduction page, TownPass connects with the App through the web-message-listeners provided by flutter_inappwebview.
Using the method provided by flutter_inappwebview, a WebMessageListener
object is registered in the WebView as an object named flutterObject
:
dart
// lib/util/web_message_handler/cp_web_message_listener.dart
WebMessageListener(
jsObjectName: 'flutterObject',
onPostMessage: (webMessage, sourceOrigin, isMainFrame, replyProxy) {
...
},
)
jsObjectName
defines the name used to access this object on the WebView side.onPostMessage
defines the logic to handle messages received from the webpage.
Writing a Custom MessageHandler
The TownPass project has simplified most of the message-passing work.
- In
lib/util/web_message_handler/cp_web_message_handler.dart
, add a new handler that extendsCPWebMessageHandler
and implement it:
dart
// lib/util/web_message_handler/cp_web_message_handler.dart
abstract class CPWebMessageHandler {
String get name;
Future<void> handle({
required String? message,
required WebUri? sourceOrigin,
required bool isMainFrame,
required Function(WebMessage replyWebMessage)? onReply,
});
WebMessage replyWebMessage({required Object data}) {
return CPWebStringMessageReply(
name: name,
data: data,
).message;
}
}
name
:Defines the handler name, corresponding to the name mentioned in Two-Way Connection on Website - Usage Design in the Project.handle
:Defines how to process the received information. Among them:message
corresponds to the data structure in Two-Way Connection on Website - Usage Design in the Project, which is the actual information that the WebView intends to send to the App.onReply
is the method to reply to the webpage, and you can usereplyWebMessage()
to construct the reply message.⚠️ Note
The
data
parameter ofreplyWebMessage()
must be a class or object that can produce a JSON string (number, boolean, string, null, list, map, or an object that implements toJson()).
- Add the new handler to the
messageHandler
list inlib/util/web_message_handler/cp_web_message_listener.dart:
dart
// lib/util/web_message_handler/cp_web_message_listener.dart
static List<CPWebMessageHandler> get messageHandler => [
UserinfoWebMessageHandler(),
LaunchMapWebMessageHandler(),
LaunchPhoneCallMessageHandler(),
// add it here
];
You can refer to the existing handlers and their implementations in the following file:
lib/util/web_message_handler/cp_web_message_handler.dart