Flutter Setup
GlamAR SDK enables real-time ar try-ons directly on Flutter, enhancing the AR experience through live camera feed and image rendering. Use the following steps to install and configure the SDK to unlock immersive AR features.
In your Flutter project, ensure that your environment is properly configured as per the Flutter setup guide for your specific case.
Installation
To integrate the Flutter SDK, install the following packages:
-
We use InAppWebView widget for adding inline native webView
-
We use Permission Handler as it offers a cross platform API to request permissions and check their status
After downloading all necessary packages we follow these steps:
Load SDK by setting the source in the InAppWebView
widget as shown below:
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';
class GlamArView extends StatefulWidget {
const GlamArView({
super.key,
});
@override
GlamArViewState createState() => GlamArViewState();
}
class GlamArViewState extends State<GlamArView> {
// Settings for iOS InAppWebView
InAppWebViewSettings settingsIos = InAppWebViewSettings(
javaScriptEnabled: true, // Enable JavaScript
transparentBackground: true, // Allow transparent background
allowsInlineMediaPlayback: true, // Allow inline media playback
allowsAirPlayForMediaPlayback: true); // Allow AirPlay for media playback
// Settings for Android InAppWebView
InAppWebViewSettings settingsAndroid = InAppWebViewSettings(
javaScriptEnabled: true, // Enable JavaScript
useHybridComposition: true, // Use hybrid composition
transparentBackground: true, // Allow transparent background
mediaPlaybackRequiresUserGesture: false, // Media playback does not require user gesture
);
late InAppWebViewController _webViewController; // Controller for the InAppWebView
@override
Widget build(BuildContext context) {
return InAppWebView(
initialUrlRequest: URLRequest(
url: WebUri('https://glamar.io/sdk'), // URL for the SDK
),
initialSettings: defaultTargetPlatform == TargetPlatform.iOS
? settingsIos // Use iOS settings if the platform is iOS
: settingsAndroid, // Use Android settings otherwise
onWebViewCreated: (controller) {
_webViewController = controller; // Assign the controller
// Once the webview is created, add an event listener to communicate with the SDK
listenGlaArEvent();
},
onPermissionRequest: (controller, permissionRequest) async {
// Handle permission requests
return onPermissionRequest(permissionRequest);
},
);
}
}
Future<PermissionResponse> onPermissionRequest(
PermissionRequest permissionRequest) async {
debugPrint('onPermissionRequest called.');
// Check if the permission request includes camera access
if (permissionRequest.resources.contains(PermissionResourceType.CAMERA)) {
// Request camera permission and check if it is granted
if (await Permission.camera.request().isGranted) {
// If granted, return a response to grant the permission
return PermissionResponse(
resources: permissionRequest.resources,
action: PermissionResponseAction.GRANT,
);
}
}
// If camera permission is not granted, do not open the SDK
return PermissionResponse(
resources: permissionRequest.resources,
action: PermissionResponseAction.DENY,
);
}
We also store the reference of the InAppWebView as
_webViewController
to use for communicating with the SDK.
If the user does not grant camera permission, do not open the SDK. Instead, handle it on the client side by providing clear instructions that camera permission is necessary for the SDK to function properly.
When the InAppWebView loads, we need to send a post message using the InAppWebView controller in the following format
_webViewController?.evaluateJavascript(source: """
window.parent.postMessage(payload, '*');
""");
Payload to initialize the SDK:
{
"type": "initialize",
"payload": {
"apiKey": "YOUR_ACCESS_KEY",
"platform": "flutter"
}
}
Replace 'YOUR_ACCESS_KEY' with your organization access key.
Event Listening
Event listeners are essential soon after initialization is called to start listening to GlamAR SDK callback events. The InAppWebView listens for messages from the SDK using the JavascriptChannel.
It is important to set handlerName to onLog
to receive messages from SDK.
void listenGlaArEvent() {
// Add a JavaScript handler to the InAppWebView controller
_webViewController.addJavaScriptHandler(
handlerName: 'onLog', // Set the handler name to 'onLog' to receive messages
callback: (args) {
// Check if the arguments list is empty
if (args.isEmpty) return;
try {
// Decode the JSON string from the first argument
final argsJson = jsonDecode(args[0]) as Map<String, dynamic>;
// Extract the 'type' field from the JSON object
final type = argsJson['type'] as String? ?? 'unknown';
// Log the event type if it's not an error
if (type == "loaded") {
debugPrint('on log event logged with loaded type');
// Once loaded event recieved we can start applying SKU's
}
if (type == "opened") {
debugPrint('on log event logged with opened type');
}
} catch (e) {
// Log an error message if JSON decoding fails
debugPrint('Error decoding JS handler args: $e');
}
},
);
}
applyBySku
Load a ar try-on using the applyBySku method by passing the relevant SKU Id.
_webViewController.evaluateJavascript(source: """
window.parent.postMessage(payload, '*');
""");
Payload
{
"type": "applyBySku",
"payload": {
"skuId": "your sku id"
}
}
Camera Permissions
Android
To handle camera permission handling for Android follow the given steps
- In
MainActivity.java
, ensureonPermissionRequest
grants camera access for WebView. - Add the required permissions in
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="true"/>
iOS
To handle camera permission handling for iOS follow the given steps
- In
Info.plist
, add the following key-value pair to request camera permissions:
<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera for showing ar try on's</string>
- Inside your podfile add the following code
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
'PERMISSION_CAMERA=1', /// This is make sure we can get camera permission
]
end
end
end