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/tp_web_message_listener.dart
WebMessageListener(
jsObjectName: 'flutterObject',
onPostMessage: (webMessage, sourceOrigin, isMainFrame, replyProxy) {
...
},
)jsObjectNamedefines the name used to access this object on the WebView side.onPostMessagedefines 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/tp_web_message_handler.dart, add a new handler that extendsTPWebMessageHandlerand implement it:
dart
// lib/util/web_message_handler/tp_web_message_handler.dart
abstract class TPWebMessageHandler {
String get name;
Future<void> handle({
required Object? message,
required WebUri? sourceOrigin,
required bool isMainFrame,
required Function(WebMessage replyWebMessage)? onReply,
});
WebMessage replyWebMessage({required Object? data}) {
return TPWebStringMessageReply(
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:messagecorresponds 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.onReplyis the method to reply to the webpage, and you can usereplyWebMessage()to construct the reply message.⚠️ Note
The
dataparameter 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
_cachedMessageHandlerslist inlib/util/web_message_handler/tp_web_message_listener.dart.messageHandlerreturns this list:
dart
// lib/util/web_message_handler/tp_web_message_listener.dart
static final List<TPWebMessageHandler> _cachedMessageHandlers = [
UserinfoWebMessageHandler(),
LaunchMapWebMessageHandler(),
PhoneCallMessageHandler(),
Agree1999MessageHandler(),
LocationMessageHandler(),
DeviceInfoMessageHandler(),
OpenLinkMessageHandler(),
NotifyMessageHandler(),
QRCodeScanMessageHandler(),
// add it here
];
static List<TPWebMessageHandler> get messageHandler => _cachedMessageHandlers;You can refer to the existing handlers and their implementations in the following file:
lib/util/web_message_handler/tp_web_message_handler.dart