ar_flutter_plugin

repository·main·Indexed 43 days ago

https://github.com/cariuslars/ar_flutter_plugin

A Flutter plugin for building collaborative Augmented Reality experiences, providing a unified interface for ARKit on iOS and ARCore on Android. It includes the ARView widget, ARAnchorManager for managing anchors and Google Cloud Anchor integration, and ARLocationManager for high-precision device location. Supports GLTF/GLB object placement, plane detection, and shared AR experiences via Firebase and Google Cloud Anchor Service. Current version ^0.7.3.

Tokens
8.6K
Snippets
34
Records
40
Agent score
56%

What's inside ar_flutter_plugin

  1. Install the ar_flutter_plugin package

    main

    You can install the ar_flutter_plugin package using the Flutter CLI or by manually editing your pubspec.yaml file.

    Using Flutter CLI:

    flutter pub add ar_flutter_plugin

    Manual Installation: Add the following to your pubspec.yaml dependencies and run flutter pub get:

    dependencies:
      ar_flutter_plugin: ^0.7.3
  2. Explore ar_flutter_plugin example applications

    main

    The plugin includes several example implementations in the Example app to demonstrate different capabilities:

    • Debug Options: Visualizes world origin, feature points, and tracked planes.
    • Local & Online Objects: Places GLTF/GLB objects from assets, web URLs, or the app's Documents directory. Includes controls for scale, position, and orientation.
    • Objects & Anchors on Planes: Creates an anchor with a 3D model attached when tapping on a detected plane.
    • Object Transformation Gestures: Extends the plane anchor example by allowing users to pan and rotate objects using gestures.
    • Screenshots: Demonstrates using the snapshot function to capture the AR scene.
    • Cloud Anchors: Enables shared AR experiences using Google Cloud Anchor Service and Firebase. Allows uploading/downloading anchors and objects within a 100m radius.
    • External Object Management: Uses Firestore to manage a database of models (requiring fields name, image, and uri pointing to a GLB file) for dynamic model selection in AR.
  3. Configure Google Cloud Anchor Service for Android

    main

    To use shared AR features with long-lived anchors (up to 365 days), you must use OAuth 2.0 authentication instead of a simple API key.

    1. Google Cloud Console Setup

    1. Activate the Cloud Anchor API.
    2. Create an OAuth 2.0 Client ID:
      • Go to Credentials in the Google Cloud Console.
      • Select New Credentials > OAuth client ID.
      • Set Application type to Android.
      • Ensure the Package name matches your AndroidManifest.xml.
      • Provide your SHA-1 certificate fingerprint. For development, use:
        keytool -keystore ~/.android/debug.keystore -list -v
    3. Configure the OAuth Consent Screen if required:
      • Add a product name and support email.
      • Add the ARCore Cloud Anchor API scope.

    2. Android Project Configuration

    Add the Google Play Services Auth dependency to your build.gradle:

    implementation 'com.google.android.gms:play-services-auth:16+'

    If using ProGuard, add these rules to your proguard-rules.pro to prevent stripping necessary classes:

    -keep class com.google.android.gms.common.** { *; }
    -keep class com.google.android.gms.auth.** { *; }
    -keep class com.google.android.gms.tasks.** { *; }
    keytool -keystore ~/.android/debug.keystore -list -v
  4. Configure Google Cloud Anchor Service for iOS

    main

    To enable Cloud Anchors on iOS, you must set up a Google Service account and include the credentials in your Xcode project.

    1. Create Service Account

    1. In Google Cloud Console, go to APIs & Services > Credentials.
    2. Select your project and click Create Credentials > Service account.
    3. Assign the role: Service Accounts > Service Account Token Creator.
    4. Once created, click the service account name, go to the Keys section, and select Add Key > Create new key.
    5. Choose JSON as the type and download the file.

    2. Xcode Integration

    1. Rename the downloaded file to cloudAnchorKey.json.
    2. Move it into your ios/Runner directory.
    3. Open Xcode, right-click the Runner directory, select Add Files to "Runner", and select your cloudAnchorKey.json file.
    4. Ensure the Runner target is selected in the dialog.
  5. Customize iOS Launch Screen Assets

    main

    To change the image displayed during the app's launch on iOS, you can either replace the image files directly in the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode for a more visual approach.

    Using Xcode:

    1. Open the iOS workspace from your project root using: open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the existing launch images.
    open ios/Runner.xcworkspace
  6. Configure Location Services for iOS

    main

    To access device location on iOS, you must add the following permission keys to your ios/Runner/Info.plist file:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This app needs access to location when open.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This app needs access to location when in the background.</string>
  7. Set up Firebase for Shared AR Experiences

    main

    The plugin's sample apps use Firebase to manage and distribute shared anchor IDs. While you can implement your own distribution method, following these steps allows you to use the provided examples.

    1. Android Setup

    1. Register your Android app in the Firebase Console using the package name from AndroidManifest.xml and your SHA-1 fingerprint.
    2. Download google-services.json and place it in the android/app directory.
    3. Add the Google services classpath to your top-level build.gradle:
      classpath 'com.google.gms:google-services:4.3.3'
    4. Apply the plugin in your app-level build.gradle:
      apply plugin: 'com.google.gms.google-services'

    2. iOS Setup

    1. Register your iOS app in the Firebase Console using the Bundle ID from Xcode's General tab.
    2. Download GoogleService-Info.plist and move it to the ios/Runner directory.
    3. In Xcode, right-click the Runner directory, select Add Files to "Runner", and select the .plist file, ensuring the Runner target is checked.

    3. Firestore

    • Enable Cloud Firestore in your Firebase project console.
    // Top-level build.gradle
    classpath 'com.google.gms:google-services:4.3.3'
    
    // App-level build.gradle
    apply plugin: 'com.google.gms.google-services'
  8. Configure iOS permissions in Podfile

    main

    If you encounter issues on iOS (such as the camera view not appearing despite having camera access), you must explicitly define permission groups in your ios/Podfile.

    Add the following configuration within the post_install block of your Podfile to enable the necessary preprocessor definitions for camera, photos, location, sensors, and bluetooth permissions.

      post_install do |installer|
        installer.pods_project.targets.each do |target|
          flutter_additional_ios_build_settings(target)
          target.build_configurations.each do |config|
            # Additional configuration options could already be set here
    
            # BEGINNING OF WHAT YOU SHOULD ADD
            config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
              '$(inherited)',
    
              ## dart: PermissionGroup.camera
              'PERMISSION_CAMERA=1',
    
              ## dart: PermissionGroup.photos
              'PERMISSION_PHOTOS=1',
    
              ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
              'PERMISSION_LOCATION=1',
    
              ## dart: PermissionGroup.sensors
              'PERMISSION_SENSORS=1',
    
              ## dart: PermissionGroup.bluetooth
              'PERMISSION_BLUETOOTH=1',
    
              # add additional permission groups if required
            ]
            # END OF WHAT YOU SHOULD ADD
          end
        end
      end
  9. Use ARAnchor to represent tracked physical entities

    main

    An ARAnchor is an abstract object attached to a tracked physical entity in the AR environment. It defines the entity's position, rotation, and scale in world coordinates using a Matrix4 transformation.

    Key properties:

    • type: The AnchorType of the anchor.
    • transformation: A Matrix4 representing rotation, translation, and scale.
    • name: A unique identifier for the anchor (autogenerated if not provided).

    You can instantiate specific anchor types or reconstruct them from JSON using the ARAnchor.fromJson factory.

    ARAnchor anchor = ARAnchor(
      type: AnchorType.plane, // Example type
      transformation: Matrix4.identity(),
      name: 'my_anchor',
    );
  10. How ARView and its managers work together

    main

    The ARView widget follows a lifecycle where it first requests camera permissions. Once granted, it instantiates a platform-specific view (AndroidARView or IosARView).

    Upon the successful creation of the platform view, the onARViewCreated callback is triggered. This callback injects four key manager instances into your application logic:

    1. ARSessionManager: Controls the AR session lifecycle.
    2. ARObjectManager: Handles the addition and management of 3D objects in the scene.
    3. ARAnchorManager: Manages anchors to fix virtual content to real-world points.
    4. ARLocationManager: Handles location-based AR features.

    You should store these manager instances in your state or a controller to interact with the AR scene after the view has loaded.

  11. Configure ARView permissions and plane detection

    main

    The ARView constructor accepts several parameters to customize the user experience and AR capabilities:

    ParameterTypeDescription
    onARViewCreatedARViewCreatedCallbackRequired. Callback receiving the four AR managers.
    planeDetectionConfigPlaneDetectionConfigConfigures which types of planes (e.g., horizontal, vertical) ARCore/ARKit should track. Defaults to PlaneDetectionConfig.none.
    showPlatformTypeboolIf true, displays the device's platform type (e.g., 'android') above the AR view. Defaults to false.
    permissionPromptDescriptionStringThe text shown when camera permission is denied.
    permissionPromptButtonTextStringThe text for the button used to request permission.
    permissionPromptParentalRestrictionStringThe text shown if permissions are restricted by the OS (iOS specific).