ios_roomplan 0.2.1
ios_roomplan: ^0.2.1 copied to clipboard
A Flutter plugin that brings Apple's RoomPlan API to iOS for single-room and multi-room scanning, with floor-plan PDFs, structured scan data, and USDZ exports. #Flutter #iOS #RoomPlan #LiDAR
ios_roomplan #
ios_roomplan is an iOS-only Flutter plugin for single-room and multi-room scanning with Apple's RoomPlan framework. Single-room capture supports iOS 16 and later; multi-room capture requires iOS 17 or later. Scan a room or connected rooms and export 2D floor-plan PDFs, structured scan data, and 3D USDZ models.
| Workflow | Minimum iOS | Results |
|---|---|---|
| Single room | iOS 16 | One ScanResult, a 2D PDF, and a 3D USDZ room model |
| Connected rooms | iOS 17 | One ScanResult per room, a multi-page 2D PDF, and a merged 3D USDZ structure |
A single-room capture produces:
- A 2D floor plan PDF generated by the plugin from the returned room geometry.
- A 3D USDZ model exported by Apple's RoomPlan framework from the native capture.
A multi-room capture returns scan data for each room, a PDF with one 2D plan per room, and one merged 3D USDZ structure.
The plugin also exposes the structured scan data to your app, including walls, detected furniture and appliances, doors, windows, openings, dimensions, transforms, confidence labels, and scan metadata. It uses Apple's native capture interface and Quick Look for file previews.
Room scans and their measurements are estimates. Results depend on device support, the room, lighting, surfaces, and how the scan is performed. Check critical dimensions on site before using them for construction, fitting, or other precision work.
Contents #
- What the plugin does
- Requirements and device support
- Install and configure
- Scan and save both outputs
- Scan multiple connected rooms
- Use the scan page
- Test multi-room scanning on an iPhone
- Preview, share, and keep the files
- Use the scanner API directly
- Save and manage scans
- Understanding the 2D floor plan
- Create multi-room floor-plan PDFs
- Review scan quality
- Data models and JSON
- Units and calculations
- Memory and performance
- Troubleshooting
- Run the example
What the plugin does #
- Checks whether Apple's RoomPlan capture session is supported on the current device.
- Requests camera permission and presents Apple's room-scanning interface.
- Streams partial geometry updates while the user scans, then returns the processed scan when the user taps Done.
- Exports the latest native capture as a parametric USDZ model.
- Creates a PDF floor plan from the processed scan geometry.
- Returns the two files to the calling Flutter screen. The app can preview them with Quick Look, copy them to persistent storage, or use the scan data in its own features.
The scan page's display options can filter furniture, doors, windows, and minimum detection confidence in the PDF and returned scan result. They do not change Apple's sensing or the native USDZ export; the USDZ represents the native capture.
Requirements and device support #
This package supports iOS only. Android, web, and desktop implementations are not provided; the scanner, file previews, and share sheet use native iOS frameworks.
- iOS 16 or later.
- A physical iPhone or iPad with a LiDAR scanner and RoomPlan support.
- Xcode and CocoaPods to build the iOS host app.
- Camera permission in the host app.
Supported device families #
RoomPlan capture requires LiDAR. The supported device families include:
- iPhone Pro and iPhone Pro Max, starting with iPhone 12 Pro / 12 Pro Max. Standard iPhone, mini, Plus, and SE models do not have the required LiDAR scanner unless Apple changes the hardware on a future model; check the actual model's specifications.
- LiDAR-equipped iPad Pro models, beginning with the 2020 generation. This includes the 11-inch iPad Pro (2nd generation and later) and 12.9-inch iPad Pro (4th generation and later), as well as later iPad Pro models with LiDAR.
The model name alone is not the final authority: Apple can change device support by hardware and OS release. At runtime, call RoomPlanScanner.isSupported(). It forwards Apple's RoomCaptureSession.isSupported result and is the definitive check for the device running your app. RoomPlan scanning is unavailable in the iOS Simulator; use a supported physical device. See Apple's RoomPlan documentation and RoomCaptureSession.isSupported.
Multi-room capture requires iOS 17 or later and a supported LiDAR device. Check RoomPlanScanner.isMultiRoomSupported() at runtime. Single-room capture remains available on iOS 16.
Install and configure #
Add the published package to your app's pubspec.yaml:
dependencies:
ios_roomplan: ^0.2.0
For local plugin development, use a path dependency instead:
dependencies:
ios_roomplan:
path: ../ios_roomplan
Set the iOS deployment target of the host app to 16.0 or later. Add a camera usage description to ios/Runner/Info.plist:
<key>NSCameraUsageDescription</key>
<string>Scan a room to create a floor plan and 3D model.</string>
The plugin prompts for camera access when scanning begins. If access was denied earlier, the user must enable it in iOS Settings.
Scan and save both outputs #
FloorRoomScanPage handles device support, capture, output creation, and error states. It returns a FloorRoomScanResult when the user completes a scan, and returns null when the page is dismissed without a result.
import 'package:flutter/material.dart';
import 'package:ios_roomplan/ios_roomplan.dart';
Future<void> scanRoom(BuildContext context) async {
final result = await Navigator.of(context).push<FloorRoomScanResult>(
MaterialPageRoute(
builder: (_) => const FloorRoomScanPage(initialName: 'Living room'),
),
);
if (!context.mounted || result == null) return;
debugPrint('Room: ${result.name}');
debugPrint('2D plan: ${result.pdfFile.path}');
debugPrint('3D model: ${result.modelFile.path}');
// Optional: read the PDF or copy either file into app-managed storage.
}
FloorRoomScanResult contains:
| Property | Meaning |
|---|---|
name |
The requested scan name, or Room Scan when the supplied name is blank. |
pdfFile |
The generated 2D plan PDF, stored in the app documents directory. |
modelFile |
The native RoomPlan USDZ export, initially stored in the system temporary directory. |
scanResult |
Processed scan geometry and metadata. This field is nullable for compatibility with callers that construct their own FloorRoomScanResult; it is populated by FloorRoomScanPage. |
libraryId |
Optional ID set by your app after saving the capture in RoomPlanScanLibrary. |
Preview, share, and keep the files #
Both files can be previewed on iOS with Quick Look:
await RoomPlanModelViewer.previewFloorPlan(result.pdfFile); // 2D PDF
await RoomPlanModelViewer.preview(result.modelFile); // 3D USDZ
previewFloorPlan expects a PDF file. preview expects a USDZ model. Both methods require the file to exist and have non-zero size.
Open the native iOS share sheet for either generated file with RoomPlanFileSharing.share(file). It returns true if a share action completes and false if the user dismisses the sheet. Sharing requires an iOS device and an existing file.
The PDF is written to the app's documents directory. The USDZ is created in the system temporary directory, which the operating system may clear. Copy it to app-managed persistent storage if it must remain available. Manage the PDF's lifecycle as well: remove old scans when no longer needed, and back up or share files according to your app's requirements.
For example, use your preferred file-sharing or storage package to copy the model before sharing or retaining it. The path is available as result.modelFile.path and its bytes can be read with await result.modelFile.readAsBytes().
Use the scanner API directly #
Use RoomPlanScanner if your app needs the structured capture data or wants to listen for incremental updates. The scanner opens Apple's capture UI; it does not provide an embedded Flutter camera view.
final scanner = RoomPlanScanner();
final subscription = scanner.onScanResult.listen((update) {
if (update == null) return;
debugPrint('Walls seen so far: ${update.room.walls.length}');
});
try {
if (!await RoomPlanScanner.isSupported()) {
throw UnsupportedError('RoomPlan is not available on this device.');
}
final scan = await scanner.startScanning();
if (scan == null) {
debugPrint('The scan was cancelled.');
return;
}
debugPrint('Final wall count: ${scan.room.walls.length}');
debugPrint('Furniture detected: ${scan.room.objects.length}');
debugPrint('Scan took ${scan.metadata.scanDuration.inSeconds} seconds');
} finally {
await subscription.cancel();
scanner.dispose();
}
Call stopScanning() to stop an active scan programmatically. Always cancel your stream subscription and call dispose() when finished. This lower-level flow returns structured scan data; use the FloorRoomScanPage workflow when you also need the plugin-generated PDF and USDZ in one operation.
Save and manage scans #
RoomPlanScanLibrary stores a scan record and copies its PDF and USDZ into app-managed persistent storage. This keeps the model available after iOS clears the temporary export. The library supports listing, reopening, renaming, deleting, and exporting/importing the structured scan record as JSON. JSON exports contain scan data and metadata, not PDF or USDZ file bytes.
final result = await Navigator.of(context).push<FloorRoomScanResult>(
MaterialPageRoute(
builder: (_) => const FloorRoomScanPage(initialName: 'Kitchen'),
),
);
if (result != null && result.scanResult != null) {
final scan = result.scanResult!;
final library = RoomPlanScanLibrary();
final saved = await library.save(
name: result.name,
scanResult: scan,
pdfFile: result.pdfFile,
modelFile: result.modelFile,
);
// These paths point to durable copies in app support storage.
debugPrint('Saved scan ID: ${saved.id}');
debugPrint('Saved model: ${saved.modelFile?.path}');
}
Reopen or manage saved entries with the same library instance:
final savedScans = await library.listScans();
if (savedScans.isNotEmpty) {
final library = RoomPlanScanLibrary();
final scan = await library.load(savedScans.first.id);
if (scan != null) {
final jsonText = await library.exportJson(scan.id);
final renamed = await library.rename(scan.id, 'Kitchen remodel');
// Restore structured data from a JSON export; output files are not included.
final imported = await library.importJson(jsonText);
debugPrint('Imported ${imported.name} as ${imported.id}');
debugPrint('Renamed saved entry to ${renamed.name}');
}
}
By default, entries are stored under the app support directory in an ios_roomplan_scans folder. Your app should decide how long to retain scans and when to delete them. JSON can be sent to another system using your preferred sharing or networking package.
Understanding the 2D floor plan #
The PDF is a top-down drawing generated from the scan's wall and opening geometry. It includes a title, room outline, dimension callouts, a compass indicator, detected door and window openings, and room summary information when geometry allows. Furniture is omitted by default in the scan page and can be enabled in its settings. Door/window visibility and the minimum confidence setting also apply to the PDF.
The drawing is fitted to a page for readability. It is intended as a visual floor-plan document; do not treat the printed page as a construction-scale drawing. Labels are calculated from RoomPlan's measured geometry. The PDF includes a reminder to verify critical dimensions on site.
The public FloorPlanPdfService API can also regenerate a plan with a title, a chosen geometry rotation, custom PlanSurfaceSnapshot values, or measurement labels enabled/disabled. surfaceSnapshots(scan) returns editable value objects that an app can adjust and pass back to create2DFloorPlan. This provides programmatic plan editing; the package does not currently include a drag-and-drop floor-plan editor UI. The current PDF dimension labels use imperial units.
An example workflow looks like this:
- Start a named capture, such as
Living room. - Slowly move around so the device can see the room's walls and openings.
- Tap Done in Apple's scan screen and wait while the plugin saves the outputs.
- Open the PDF to inspect the top-down plan and the USDZ to inspect the 3D room.
- Re-scan missed areas or objects; measure critical dimensions manually.
Scan multiple connected rooms #
On iOS 17 and later, the plugin can scan connected rooms in one shared coordinate space and export them as a single 3D USDZ structure. The native scan screen asks whether to scan another room or finish the structure after each room. Move between adjacent rooms without ending the capture session, and keep the device tracking stable; tracking interruptions or large disconnected areas can prevent accurate alignment. See Apple's multi-room scanning guide.
if (await RoomPlanScanner.isMultiRoomSupported()) {
final structure = await RoomPlanScanner().startMultiRoomScanning();
print('Captured ${structure.rooms.length} rooms');
print('Merged 3D model: ${structure.modelFile.path}');
final pdf = await FloorPlanPdfService.createMultiRoom2DFloorPlan(
structure.rooms,
title: 'Home',
fileName: 'home_floor_plans',
);
}
The returned room list contains one ScanResult per captured room. The PDF has one top-down plan per room; it does not infer room placement from the PDFs. The USDZ is built by Apple's StructureBuilder from the native captures, checked to contain every captured room, and exported as a mesh so all room surfaces and openings can be viewed together in Quick Look. Copy output files to app-managed storage if they need to outlive the temporary capture directory.
FloorRoomScanPage(initialName: 'Home', multiRoom: true) provides the same workflow with a scan page and PDF generation.
Use the scan page #
The scan page handles the native camera flow, scan settings, PDF generation, and result packaging. Open it with multiRoom: true to scan connected rooms:
final result = await Navigator.of(context).push<FloorRoomScanResult>(
MaterialPageRoute(
builder: (_) => const FloorRoomScanPage(
initialName: 'Home',
multiRoom: true,
),
),
);
if (!context.mounted || result == null) return;
// `rooms` has one ScanResult per captured room.
debugPrint('Rooms: ${result.rooms.length}');
debugPrint('2D plans: ${result.pdfFile.path}');
debugPrint('Merged 3D model: ${result.modelFile.path}');
await RoomPlanModelViewer.previewFloorPlan(result.pdfFile);
await RoomPlanModelViewer.preview(result.modelFile);
For a multi-room result, scanResult is null and rooms contains the per-room scans. The PDF has one page per room; the USDZ is Apple's merged structure model. FloorRoomScanPage shows the native scan and processing states, but the app remains responsible for copying temporary USDZ output when it needs long-term storage.
Test multi-room scanning on an iPhone #
Use a physical LiDAR-equipped iPhone Pro running iOS 17 or later. The iOS Simulator can build the example app, but cannot scan rooms.
-
From the repository, prepare and launch the example on your iPhone:
cd example flutter pub get cd ios && pod install && cd .. flutter run -
Tap Scan connected rooms (iOS 17+) and allow camera access.
-
Scan the first room slowly, keeping its walls and doorways visible. Tap Finish Room in the native scanner.
-
Tap Scan Another Room, walk through a doorway into an adjacent room, and scan it.
-
Tap Finish Room, then choose Finish Structure.
-
Confirm the example reports multiple rooms. Preview the 2D PDF (one page per room) and the merged 3D USDZ. The model is assembled by Apple's
StructureBuilderfrom rooms captured in the shared coordinate space; it does not stitch unrelated scans or let the user manually align rooms. Use the share buttons to save or send either file.
For reliable alignment, scan adjacent rooms in the same session and keep moving between rooms without interrupting tracking. If the structure cannot be merged, try again with steadier movement and a clear view through the doorway. Apple’s guide to scanning the rooms of a single structure explains the native multi-room workflow and coordinate-space requirements.
Create multi-room floor-plan PDFs #
FloorPlanPdfService.createMerged2DFloorPlan creates one PDF page for each saved room scan. This is useful for keeping several room plans in a single document:
final scans = await library.listScans();
final rooms = scans
.where((scan) => scan.pdfFile != null)
.map((scan) => NamedScanResult(
name: scan.name,
scanResult: scan.scanResult,
pdfFile: scan.pdfFile!,
))
.toList();
final combinedPdf = await FloorPlanPdfService.createMerged2DFloorPlan(
rooms,
title: 'Apartment room plans',
fileName: 'apartment_room_plans',
);
await RoomPlanModelViewer.previewFloorPlan(combinedPdf);
For a single-page composed layout, createArrangedMerged2DFloorPlan accepts ArrangedScanResult values with per-room offsets and rotations. It can also control measurement visibility and north rotation. Your app supplies the placement coordinates; the package does not automatically infer how rooms connect.
Data models and JSON #
The top-level ScanResult groups the processed room, capture metadata, and a confidence summary:
| Model | Fields and purpose |
|---|---|
ScanResult |
room, metadata, and confidence. |
RoomData |
Optional room dimensions; lists of walls, objects, doors, windows, and openings; optional floor and ceiling. Fields may be absent when RoomPlan does not return that geometry. |
WallData |
Stable uuid, position, width, height, confidence, nested openings, optional dimensions, and optional 4×4 transform. points is available in the model but is currently empty in the native RoomPlan mapping. |
ObjectData |
Detected object category, position, width, height, length, confidence, optional dimensions, and transform. Categories include storage, table, sofa, chair, bed, sink, toilet, oven, refrigerator, stove, washer/dryer, or unknown. |
OpeningData |
Door, window, or generic opening type, position, width, height, confidence, optional dimensions, and transform. |
Position |
A 3D point (x, y, z) in the RoomPlan coordinate space. |
RoomDimensions |
Length, width, and height in meters, with derived area, volume, and perimeter helpers. |
ScanMetadata |
Scan date, elapsed duration, device model reported by iOS, and whether LiDAR was used. |
ScanConfidence |
Overall, wall, and dimension confidence summary values plus warnings. |
Confidence |
RoomPlan's per-element high, medium, or low label. |
The native payload includes the processed room geometry and device/timing metadata. Matrix transforms are provided as 16 numeric values and are useful when positioning geometry in 3D. RoomPlan values and transforms are passed through the Dart models; position and dimensions are measured in meters. Optional values can be null, and detection lists can be empty. The plugin maps unknown object categories to ObjectCategory.unknown and unknown confidence strings to Confidence.low.
The current native payload does not populate the room-level RoomData.dimensions field, and it does not map mesh vertices into WallData.points. The PDF draws from the returned wall and opening geometry and calculates a footprint-based area label when a room-level area is not present. Do not assume every optional model field contains a measured value in every scan.
ScanConfidence values are confidence indicators, not measured error margins. The current parser derives these 0–1 summary values by averaging RoomPlan's categorical labels (high, medium, and low) across detected walls and objects. In particular, dimensionAccuracy is currently based on object confidence labels; it is not a guarantee that a dimension is accurate to a stated tolerance.
Models support toJson() and fromJson() for app-side persistence or transport. Example:
final Map<String, dynamic> storedScan = scan.toJson();
final restoredScan = ScanResult.fromJson(storedScan);
final jsonText = jsonEncode(storedScan);
Add import 'dart:convert'; to use jsonEncode. Keep your own schema/versioning strategy if you persist scan JSON long-term, because Apple's RoomPlan output and plugin model fields can evolve.
Review scan quality #
RoomPlanScanQuality.fromScan(scan) creates user-facing review hints from the captured wall and object detections. It reports the detected wall count and low-confidence detection ratio, and suggests reviewing or rescanning when geometry is sparse or many detections have low confidence.
final review = RoomPlanScanQuality.fromScan(scan);
for (final suggestion in review.suggestions) {
debugPrint(suggestion);
}
These hints can help users decide whether to inspect a result more closely. They cannot detect surfaces that RoomPlan missed, and they are not an accuracy score or a substitute for checking measurements on site.
Units and calculations #
RoomPlan geometry and Position coordinates use meters internally. RoomDimensions stores its length, width, and height in meters. Choose MeasurementUnit.metric or MeasurementUnit.imperial for display; conversion helpers do not change the stored scan values.
final dimensions = scan.room.dimensions;
if (dimensions != null) {
final area = dimensions.getFormattedFloorArea(MeasurementUnit.metric);
final volume = dimensions.getFormattedVolume(MeasurementUnit.imperial);
final perimeter = dimensions.getFormattedPerimeter(MeasurementUnit.metric);
debugPrint('Area $area, volume $volume, perimeter $perimeter');
}
The RoomDimensions convenience calculations assume a rectangular room:
| Calculation | Formula | Units |
|---|---|---|
| Floor area | length × width |
m² or sq ft |
| Volume | length × width × height |
m³ or cu ft |
| Perimeter | 2 × (length + width) |
m or ft |
For example, dimensions of 5 m × 4 m × 2.8 m give a calculated rectangular floor area of 20 m², perimeter of 18 m, and volume of 56 m³. These are derived values, not independent sensor readings. Irregular floor plans, alcoves, sloped walls, or incomplete scans are not represented by those rectangular formulas. The PDF's footprint calculations use the geometry available for its drawing and can differ from the model getter formulas.
UnitConverter converts lengths with 1 m = 3.28084 ft, area with 1 m² = 10.7639 sq ft, and volume with 1 m³ = 35.3147 cu ft. Formatting defaults to two decimal places and can be changed with the decimals argument.
Memory and performance #
RoomPlan capture and 3D export run in Apple's native framework. Multi-room merging requires keeping each completed CapturedRoom available until StructureBuilder finishes, so memory use increases with the size and number of rooms. The plugin throttles partial scan updates sent to Flutter to about two per second, stops an active scan safely when iOS reports memory pressure, and releases native room data and pauses AR when the capture finishes.
For apps processing many or large scans:
- Keep only the scan data and model files needed for the current screen; release references and cancel stream subscriptions when a screen closes.
- Scan connected rooms in one continuous session, avoid sending the app to the background, and finish the structure before starting another capture.
- Keep multi-room captures to a practical residential area. Apple's WWDC23 guidance recommends about 186 m² (2,000 sq ft) or less per merged structure for best results; this is guidance, not an enforced plugin limit.
- Avoid repeatedly serializing large
ScanResultobjects or reading whole PDF/USDZ files into memory when a streaming or file-based workflow is available. - Copy temporary USDZ files only when retaining or sharing them, and delete old generated files when your app's retention policy allows.
- Handle
MemoryPressureExceptionand let the user retry with a smaller structure after closing other apps. The plugin does not read or enforce a device-wide memory budget.
The repository includes mapper and object-pool helpers for Dart-side work. These helpers are not part of Apple's capture pipeline and are not integrated into the native RoomPlan processing. They do not reduce Apple's sensor workload, guarantee lower memory use, or replace profiling on physical devices. PerformanceMonitor does not currently read actual iOS memory statistics, so its memory-monitoring hooks should not be used as authoritative memory telemetry.
Troubleshooting #
| Symptom | What to check |
|---|---|
| Scanning is unavailable | Confirm iOS 16+, LiDAR hardware, and await RoomPlanScanner.isSupported() on a physical device. Simulator builds cannot scan. |
| Camera access is denied | Add NSCameraUsageDescription; ask the user to enable camera access for the app in iOS Settings. |
| A scan has missing walls or objects | Scan more slowly, keep the room and corners in view, improve lighting, and make another pass over missed surfaces. RoomPlan detections vary by room and device. |
The scan returns null |
The capture was cancelled. Start a new scan if appropriate. |
| A file preview fails | Confirm the file exists, is non-empty, and has the expected type (PDF for the floor plan or USDZ for the 3D viewer). |
| A retained USDZ disappeared | USDZ exports start in temporary storage. Copy the file to persistent app storage soon after export. |
| Capture or export fails | Catch RoomPlanException (including its subclasses), show its message, and let the user retry. Low available memory or invalid/empty geometry may also prevent output creation. |
Run the example #
Run Flutter package resolution from the example app first. This generates example/ios/Flutter/Generated.xcconfig, which the CocoaPods Podfile reads:
cd example
flutter pub get
cd ios
pod install
cd ..
flutter run
Run it on a supported physical iPhone or iPad. The example screen starts a scan and then offers separate buttons to preview and share the generated 2D PDF and 3D USDZ. Grant camera access when prompted. The iOS Simulator can build the example, but it cannot perform a RoomPlan scan.
License #
MIT. See LICENSE.