π SUPPORT THE PROJECT
If you find this package useful, consider supporting its development: Donate via PayPal β
β οΈ DISCLAIMER - PRIVATE USE ONLY
This package is intended for private use only and is provided without any warranty or guarantee of correct functionality. The software is developed 100% by AI with human supervision using advanced code generation techniques.No Support Provided: This is an experimental project - use at your own risk. The authors assume no responsibility for any issues, data loss, or damages that may occur from using this software.
This package is built using the "vibe coding" development methodology - an AI-driven approach that emphasizes rapid iteration, creative problem-solving, and adaptive architecture. Here's what this means for users:
- AI-First Development: Code is generated by advanced AI models with human supervision and direction
- Rapid Prototyping: Features are implemented quickly through iterative AI-human collaboration
- Creative Architecture: Solutions often explore unconventional approaches that traditional development might overlook
- Continuous Evolution: The codebase evolves through constant refinement and improvement
- Fast Feature Delivery: New capabilities can be implemented and tested rapidly
- Innovative Solutions: AI can suggest creative approaches to complex problems
- Adaptive Design: Architecture can pivot quickly based on emerging requirements
- Comprehensive Coverage: AI can generate extensive test suites and documentation
- Experimental Nature: This approach is cutting-edge and may produce unexpected behaviors
- Learning Curve: The AI may explore patterns that differ from conventional Flutter development
- Potential Quirks: Some implementations might be unconventional but functional
- No Traditional Support: Issues are addressed through iterative improvement rather than traditional bug-fix cycles
While this is an experimental approach, we're committed to:
- Thorough testing of core functionality
- Clear documentation of capabilities and limitations
- Continuous improvement based on user feedback
- Transparency about the development methodology
We recommend thorough testing in your specific use case before production deployment.
- π― Improved Auto-Crop Pipeline: Advanced Cannyβdilateβlargest contourβwarp pipeline with intelligent fallback support
- β‘ Lightning Fast Processing: Auto-crop processes images in under 100ms with confidence scoring and bounding box fallback
- π§ Smart Edge Detection: Cached, downscaled detection with adaptive thresholding for optimal performance
- π Processing Metadata: Detailed reporting of duration, confidence scores, and fallback usage for transparency
- π¨ Enhanced Onboarding: Improved first-scan experience with contextual guidance and streamlined navigation
- π± Prioritized Navigation: Reorganized tabs to prioritize scanning workflows (Quick Scan β Multi Scan β Lab)
- π― First-Scan Guidance: Helpful banners and tips appear for new users to guide them through the app
- π Streamlined Workflows: Better integration between scanning, editing, and PDF generation phases
- π What's New in 2.1.0
- π Vibe Coding Development Philosophy
- β¨ Features
- π Support This Project
- π¦ Installation
- π± Example App
- π Usage
- ποΈ Architecture
- π API Reference
- πΊοΈ Roadmap
- π§ͺ Testing & Debugging
- π€ Contributing
- π License
A Flutter package for scanning documents, receipts, and manuals with automatic cropping, filtering, and PDF generation. Now with Multi-Page Support!
- πΈ Single & Multi-Page Scanning: Scan individual pages or combine multiple pages into one document
- πΈ Document Scanning: Camera and gallery support for document capture
- π¨ Advanced Image Processing: Automatic cropping, grayscale conversion, contrast enhancement
- π€ Auto-Crop Pipeline: Advanced Cannyβdilateβlargest contourβwarp pipeline with fallback support
- β‘ Fast Auto-Crop: Processes images in <100ms with confidence scoring and bounding box fallback
- β¨ Image Editing: Post-capture editing with rotation, color filters, and cropping
- π True Perspective Correction: Transform quadrilateral selections into perfect rectangles
- π Document Format Support: A4, Letter, Square formats with proper aspect ratios
- π Clean PDF Generation: Minimal PDF output without headers/footers (multi-page shows page numbers only)
- πΌοΈ Optimized Color Filters: Enhanced and B&W filters preserve faded text visibility
- π± QR Code Scanning: Automatic manual download from QR codes
- π Multiple Document Types: Receipts, manuals, documents with specific processing
- πΎ External Storage: Safe storage outside app directory with descriptive naming
- βοΈ Customizable Processing: Configurable image processing options
- π Page Management: Add, remove, reorder, and preview pages in multi-page documents
- πΎ Flexible Output: Choose between PDF-only (default) or PDF + image file
- β‘ Performance Optimized: Images auto-resized to 2000px for fast processing (<3s)
- π Background Processing: UI never freezes - all heavy operations run in background isolates
- π§ Smart Edge Detection: Cached, downscaled detection with adaptive thresholding
- π Resize Metadata: Tracks original and resized dimensions for accurate processing
- π Auto-Crop Metadata: Reports duration, confidence, and fallback usage for each auto-crop operation
If you find this package useful and want to support its continued development, please consider a donation:
Your support helps:
- Maintain and improve the package
- Add new features and capabilities
- Provide comprehensive documentation
- Keep the project open-source and accessible
Every contribution, no matter how small, is greatly appreciated! π
Add this package to your Flutter project:
dependencies:
document_scanner:
path: packages/document_scannerThe package includes a comprehensive example application that demonstrates all features and capabilities. The example app serves as both a showcase and a testing ground for the library.
- Single Page Capture β Complete scanning workflow with image editing
- Multi-Page Session Lab β Advanced multi-page document management
- PDF Review Center β Preview and manage scanned documents
- Capabilities Lab β Interactive playground for testing different configurations
cd example
flutter pub get
flutter runThe example app provides:
- Real-time testing of all scanning features
- Configuration options for storage and processing
- Visual feedback and debugging information
- Complete workflow demonstrations
For detailed setup instructions and troubleshooting, see example/README.md.
Before using any scanning functionality, you must configure the storage settings:
import 'package:document_scanner/document_scanner.dart';
// Configure storage (call this once at app startup)
DocumentScannerService().configureStorage(
appName: 'MyApp', // Your app name for directory creation (used only when customStorageDirectory is not provided)
customStorageDirectory: '/custom/path', // Optional: exact custom directory path (when provided, appName is ignored)
pdfBrandingText: 'Generated by MyApp', // Optional: custom PDF footer text
);import 'package:document_scanner/document_scanner.dart';
// Scan a single receipt (opens image editor automatically)
final result = await DocumentScannerService().scanDocument(
documentType: DocumentType.receipt,
processingOptions: DocumentProcessingOptions.receipt,
customFilename: 'MyReceipt',
);
// Note: This returns raw document for editing - use finalizeScanResult() after editing
if (result.success) {
print('Document captured: ${result.document?.id}');
} else {
print('Error: ${result.error}');
}import 'package:document_scanner/document_scanner.dart';
// Scan and process directly - returns final document with paths
final result = await DocumentScannerService().scanDocumentWithProcessing(
documentType: DocumentType.receipt,
processingOptions: DocumentProcessingOptions.receipt,
customFilename: 'MyReceipt',
);
if (result.success) {
print('PDF saved: ${result.document?.pdfPath}');
print('Processed image: ${result.document?.processedPath}');
} else {
print('Error: ${result.error}');
}// Use the multi-page scanner widget
MultiPageScannerWidget(
documentType: DocumentType.manual,
customFilename: 'ProductManual',
onScanComplete: (result) {
if (result.success) {
print('Multi-page document created: ${result.document?.pdfPath}');
print('Pages scanned: ${result.document?.pages.length}');
}
},
)- Start Scanning: Scan the first page
- Add More Pages: Continue scanning additional pages
- Preview & Manage: View thumbnails, preview pages, reorder, or delete pages
- Finalize: Combine all pages into a single optimized PDF
DocumentScannerWidget(
documentType: DocumentType.receipt,
showQROption: true,
onScanComplete: (result) {
if (result.success) {
// Handle successful scan
} else {
// Handle error
}
},
)// Scan QR code
final qrResult = await DocumentScannerService().scanQRCode();
if (qrResult.success && qrResult.contentType == QRContentType.manualLink) {
// Download manual from QR code URL
final downloadResult = await DocumentScannerService().downloadManualFromUrl(
url: qrResult.qrData,
customFilename: 'ProductManual',
);
}final customOptions = DocumentProcessingOptions(
convertToGrayscale: true,
enhanceContrast: true,
autoCorrectPerspective: true,
compressionQuality: 0.9,
generatePdf: true,
saveImageFile: false, // Default: PDF only, set true for PDF + image
);
final result = await DocumentScannerService().scanDocument(
documentType: DocumentType.document,
processingOptions: customOptions,
);By default, the package saves only the final PDF file for optimal storage usage:
// Default behavior - PDF only (recommended)
final options = DocumentProcessingOptions(
generatePdf: true,
saveImageFile: false, // Default
);
// Optional - Save both PDF and processed image
final optionsWithImage = DocumentProcessingOptions(
generatePdf: true,
saveImageFile: true, // Saves both PDF and .jpg
);The package now includes a comprehensive image editing screen that automatically appears after every image capture, allowing users to perfect their scanned documents in real-time:
- 90Β° Clockwise: Rotate image right with dedicated button
- 90Β° Counterclockwise: Rotate image left with dedicated button
- Multiple rotations: Apply multiple 90Β° rotations as needed
- Original: Keep original colors (default)
- Enhanced: Histogram equalization with clip limit to increase contrast and clarity without over-saturation. Uses per-channel processing to preserve colors while boosting visibility of faint text and details.
- B&W: Adaptive black & white conversion using Otsu's method for automatic thresholding. Uses proper luminance calculation (0.299R + 0.587G + 0.114B) to preserve line work and text readability across varying lighting conditions.
- Auto-detection: Automatically detect document boundaries
- Interactive overlay: Visual crop boundaries with corner handles
- Manual adjustment: Fine-tune crop area as needed
- True perspective correction: Transform quadrilateral selection into perfect rectangle
- Document format support: Choose A4, Letter, Square, or Auto aspect ratios
- Orientation-aware: Automatically handles portrait/landscape after rotation
The image editor is now automatically integrated into both single-page and multi-page workflows:
- Capture image with camera or import from gallery
- Editor opens automatically with the captured image
- User edits (rotate, filter, crop) or can skip editing
- Finalizes with PDF generation and external storage
- Scan first page β Editor opens automatically
- Add more pages β Editor opens for each new page
- Manage pages β Preview, reorder, delete as needed
- Finalize document β All pages combined into single PDF
If you need to show the editor manually in custom workflows:
import 'package:document_scanner/document_scanner.dart';
// Manual editor integration
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ImageEditingWidget(
imageData: capturedImageData,
onImageEdited: (editedImageData) {
// Handle the edited image
print('Image edited successfully');
Navigator.pop(context);
},
onCancel: () {
// Handle cancel
Navigator.pop(context);
},
),
),
);// Configure editing options programmatically
final editingOptions = ImageEditingOptions(
rotationDegrees: 90, // 0, 90, 180, 270
colorFilter: ColorFilter.highContrast,
cropCorners: [ // 4 corner points for cropping
Offset(50, 50), // Top-left
Offset(350, 60), // Top-right
Offset(340, 450), // Bottom-right
Offset(60, 440), // Bottom-left
],
);
// Apply editing options directly
final editedImageData = await ImageProcessor().applyImageEditing(
originalImageData,
editingOptions,
);// Detect document edges automatically
final corners = await ImageProcessor().detectDocumentEdges(imageData);
// Use detected corners for cropping
final croppedImage = await ImageProcessor().applyImageEditing(
imageData,
ImageEditingOptions(cropCorners: corners),
);- Add Pages: Continue scanning additional pages seamlessly
- Page Thumbnails: Visual grid view of all scanned pages
- Page Preview: Fullscreen preview with zoom and navigation
- Delete Pages: Remove unwanted pages from the document
- Reorder Pages: Drag and drop to change page order
- Individual Processing: Each page processed with same settings
- Batch Processing: Efficient processing of multiple pages
- Unified PDF: All pages combined into single optimized PDF
- Clean Output: Minimal PDF design with maximum space for content
The package generates clean, professional PDFs optimized for document scanning:
- Minimal design: No headers, footers, or branding
- Maximum content space: 5px margins only
- Centered image: Proportionally scaled to fit page
- Clean output: Focus on document content
- Page numbers only: Discrete page counter (e.g., "2/5") in bottom-right
- Consistent layout: Same clean design across all pages
- No metadata clutter: No scan dates, app info, or branding
// Multi-page scanner with full page management
MultiPageScannerWidget(
documentType: DocumentType.manual,
processingOptions: DocumentProcessingOptions.manual,
onScanComplete: (result) {
// Handle completed multi-page document
},
)- Grayscale conversion for better text readability
- High contrast enhancement for faded receipts
- Automatic cropping to document boundaries (manual/guided mode)
- Multi-page support for long receipts
- Color preservation for diagrams and illustrations
- QR code support for automatic download
- URL validation and metadata extraction
- Multi-page support for complex instruction manuals
- Chapter organization with page management
- Balanced processing for general documents
- Perspective correction for angled scans
- Adaptive processing based on content type
- Multi-page support for contracts, forms, reports
The package uses a flexible, hierarchical naming system:
- Custom Filename: If provided via
customFilenameparameter - Product-Based:
YYYY-MM-DD_Brand_Model_Type.pdf(when brand/model available) - Timestamp Fallback:
YYYYMMDD_Type.pdf(when no product details)
- With Product Info:
2025-01-09_Samsung_GalaxyS24_Receipt.pdf - Custom Name:
MyCustomReceipt_Receipt.pdf - Timestamp Fallback:
20250109_Receipt.pdf - Multi-Page:
2025-01-09_LG_Washer_Manual.pdf
// Pass product details for intelligent naming
final result = await DocumentScannerService().scanDocument(
documentType: DocumentType.receipt,
customFilename: 'CustomName', // Highest priority
// Or let the service generate from metadata:
// metadata: {
// 'productBrand': 'Samsung',
// 'productModel': 'Galaxy S24',
// 'purchaseDate': '2025-01-09',
// }
);Documents are stored in configurable external storage for safety:
- Android:
- Default:
/storage/emulated/0/Documents/{AppName}/ - Custom: Exact path specified in
customStorageDirectory
- Default:
- iOS:
- Default: App documents directory
- Custom: Exact path specified in
customStorageDirectory
- Organization: Automatic folder creation and file management
The storage directory behavior depends on the configuration:
- When
customStorageDirectoryis provided: Uses the exact path specified, ignoringappName - When
customStorageDirectoryis NOT provided: Uses/storage/emulated/0/Documents/{appName}/on Android
// Default configuration (uses 'DocumentScanner' as app name)
DocumentScannerService().configureStorage(
appName: 'MyApp',
);
// Custom storage path (exact directory - appName will be ignored)
DocumentScannerService().configureStorage(
appName: 'MyApp', // This will be ignored when customStorageDirectory is provided
customStorageDirectory: '/storage/emulated/0/Documents/MyApp', // Exact final directory path
);
// Custom PDF branding
DocumentScannerService().configureStorage(
appName: 'MyApp',
pdfBrandingText: 'Generated by MyApp v2.0',
);// Create a multi-page session
final session = MultiPageScanSession(
sessionId: 'unique_session_id',
documentType: DocumentType.manual,
processingOptions: DocumentProcessingOptions.manual,
startTime: DateTime.now(),
);
// Add pages progressively
session = session.addPage(scannedPage1);
session = session.addPage(scannedPage2);
// Reorder pages
session = session.reorderPages(reorderedPageList);
// Convert to final document
final finalDocument = session.toScannedDocument();The package requires the following permissions:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" /><key>NSCameraUsageDescription</key>
<string>This app needs camera access to scan documents</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs photo library access to import documents</string>DocumentScannerService
βββ ImageProcessor (cropping, filtering, enhancement)
βββ PdfGenerator (single & multi-page PDF creation)
βββ QRScannerService (QR scanning and manual download)
βββ DocumentScannerWidget (single page UI)
βββ MultiPageScannerWidget (multi-page UI with management)
configureStorage()- Configure storage paths and branding (required)scanDocument()- Scan single page with camera (returns raw document for editing)importDocument()- Import single page from gallery (returns raw document for editing)scanDocumentWithProcessing()- Scan and process directly (returns final document with paths)importDocumentWithProcessing()- Import and process directly (returns final document with paths)finalizeScanResult()- Process and save edited document (used by widgets)scanQRCode()- Scan QR code for manual downloaddownloadManualFromUrl()- Download manual from URL
MultiPageScanSession- Manages progressive scanning workflowDocumentPage- Represents individual pages in multi-page documentsMultiPageScannerWidget- Complete UI for multi-page scanning
ImageEditingWidget- Complete UI for post-capture image editingImageEditingOptions- Configuration for rotation, filters, and croppingColorFilter- Enum for color filter options (none, highContrast, blackAndWhite)ImageProcessor.applyImageEditing()- Apply editing options to image dataImageProcessor.detectDocumentEdges()- Auto-detect document boundaries
convertToGrayscale- Convert to grayscaleenhanceContrast- Enhance contrastautoCorrectPerspective- Auto-correct perspectivecompressionQuality- JPEG compression qualitygeneratePdf- Generate PDF output
receipt- Receipt processing (supports multi-page)manual- Manual processing (optimized for multi-page)document- General document processingother- Custom processing
We're planning exciting enhancements to make document scanning even more powerful and automated:
- Automatic Text Recognition: Extract text from scanned documents using advanced OCR engines
- Intelligent Filename Generation: Auto-generate descriptive filenames based on extracted content
- Content-Based Organization: Automatically categorize documents by detected content (invoices, contracts, receipts, etc.)
- Searchable PDFs: Embed text layers in PDFs for full-text search capabilities
- Data Extraction: Pull out key information like dates, amounts, vendor names from receipts
- Smart Background Detection: Automatically identify and isolate white paper from complex backgrounds
- Advanced Perspective Correction: Enhanced algorithms for perfect document alignment
- Auto-Crop Intelligence: Intelligent boundary detection that handles edge cases like shadows, folds, and curved pages
- Lighting Compensation: Automatic brightness and contrast adjustment for varying lighting conditions
- Multi-Layer Processing: Separate processing for text regions and graphics for optimal quality
- Batch Processing: Process multiple documents simultaneously with queue management
- Cloud Integration: Direct upload to cloud storage services (Google Drive, Dropbox, OneDrive)
- Advanced Filters: Specialized filters for different document types (blueprints, photos, forms)
- Annotation Support: Add text annotations, highlights, and signatures to scanned documents
- Template Recognition: Identify and process common document templates automatically
- Machine Learning Models: Custom-trained models for specific document types
- Real-Time Preview: Live preview of processing results before capture
- Multi-Language OCR: Support for text extraction in multiple languages
- API Integration: Connect to external services for data validation and processing
Have ideas for Phase 3 or beyond? We'd love to hear from you! While we don't offer traditional support, community feedback helps shape our development priorities. Feel free to share your thoughts through GitHub issues or discussions.
- Page Order: Scan pages in the desired final order when possible
- Consistent Lighting: Maintain consistent lighting across all pages
- Quality Check: Preview each page before adding the next
- Page Limits: Consider device memory when scanning many pages
- Error Handling: Always handle scan failures gracefully
- Memory Management: Pages are processed individually to minimize memory usage
- Background Processing: Image processing happens off the main thread
- Progressive Loading: Thumbnail generation is optimized for performance
- Storage Optimization: PDF compression reduces file sizes significantly
The /example directory now contains a multi-screen demo that mirrors the rebuilt library APIs:
- Single Page Capture β launches
DocumentScannerWidget, routes through the built-in editor +PdfPreviewWidget, and surfaces saved paths/metadata. - Multi-Page Session Lab β demonstrates
MultiPageScannerWidgetincluding the grid, preview/reorder dialog, and final PDF generation. - PDF Review Center β uses
PdfPreviewWidgetagainst previously savedScannedDocumentinstances, reading bytes from disk when required. - Capabilities Lab β interactive playground for
DocumentProcessingOptionsthat callsscanDocumentWithProcessingandimportDocumentWithProcessingdirectly, so you can toggle grayscale, compression, DPI, formats, and filenames.
Placeholder captures you can replace with real screenshots/GIFs:

cd example
flutter pub get
flutter runUse the configuration card on the home screen to call DocumentScannerService().configureStorage() with an app name, optional custom directory, and default filename before running the flows.
Run these steps on a device/emulator to validate Phase 2 end-to-end (also surfaced inside the app via the clipboard icon):
- Apply a custom app name + storage directory, capture a single page, and confirm the generated files land in that directory with the configured filename.
- Complete a single-page scan (edit + preview) and verify the detail card shows a preview image, metadata table, and paths.
- Create a multi-page session with at least three pages, reorder once, finalize the PDF, and confirm the page list reflects the correct order/count.
- Open the PDF review screen and preview the documents generated in the previous steps.
- In the capabilities lab, disable grayscale, enable "save processed image", set the PDF resolution to
original, then run both camera and gallery experiments β verify two output paths (PDF + image) are listed. - Trigger an error (deny permission or cancel mid-flow) and ensure it is captured in the home timeline with the proper status chip.
For additional screenshots, troubleshooting tips, and platform notes see example/README.md.
We welcome contributions to the document_scanner package! This open-source project thrives on community involvement, whether you're fixing bugs, adding features, or improving documentation.
For detailed contribution guidelines, setup instructions, and development workflow, please see our comprehensive CONTRIBUTING.md guide.
- π Contribution Guidelines - Complete development setup and workflow
- π Report Issues - Bug reports and feature requests
- π¬ Discussions - Community questions and ideas
- π± Example App - Testing and development playground
- π§ Core Services: Enhance image processing, PDF generation, or camera handling
- π¨ UI Components: Improve widgets, add new editing features, enhance UX
- π± Platform Support: Add platform-specific optimizations (iOS, Android)
- π§ͺ Testing: Expand test coverage, add integration tests, improve test utilities
- π Documentation: Improve README, add examples, create guides
- π Performance: Optimize memory usage, processing speed, file handling
Remember: This project uses the "vibe coding" methodology, so we value creative solutions and rapid iteration. Don't be afraid to experiment with unconventional approaches!
This section provides comprehensive guidance for testing and debugging the document_scanner package during development.
- Flutter 3.0+: Ensure you have the latest stable Flutter SDK
- Android Studio/Xcode: For platform-specific debugging
- Physical Device: Recommended for camera testing (emulator has limitations)
- Git: For version control and collaboration
# Clone the repository
git clone <repository-url>
cd document_scanner
# Get all dependencies
flutter pub get
# Install development dependencies
flutter pub dev_dependencies
# Generate mocks (if making changes to services)
flutter pub run build_runner build --delete-conflicting-outputs
# Run initial tests to verify setup
flutter test# Run all unit tests
flutter test --unit-test
# Run specific service tests
flutter test test/services/
flutter test test/models/
flutter test test/ui/
# Run with coverage report
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html# Run integration tests
flutter test integration_test/
# Run on specific device
flutter test -d <device-id> integration_test/
# Run with detailed logging
flutter test --verbose integration_test/# Run widget tests
flutter test test/widget_tests/
# Golden tests (visual regression)
flutter test --update-goldens test/widget_tests/golden_tests/// Debug camera permissions
import 'package:permission_handler/permission_handler.dart';
// Check current permission status
var cameraStatus = await Permission.camera.status;
var storageStatus = await Permission.storage.status;
print('Camera permission: $cameraStatus');
print('Storage permission: $storageStatus');
// Request permissions if needed
if (await Permission.camera.request().isGranted) {
print('Camera permission granted');
}// Debug image processing pipeline
import 'package:document_scanner/document_scanner.dart';
// Enable debug logging
ImageProcessor.setDebugMode(true);
// Process with debug info
final result = await ImageProcessor().processImage(
imageData,
options: DocumentProcessingOptions(),
onProgress: (progress) {
print('Processing progress: ${(progress * 100).toInt()}%');
},
);
print('Processing result: ${result.success}');
print('Error: ${result.error}');
print('Processing time: ${result.processingTime}ms');// Debug storage configuration
import 'package:document_scanner/document_scanner.dart';
// Check storage configuration
final service = DocumentScannerService();
await service.configureStorage(
appName: 'DebugApp',
customStorageDirectory: '/debug/path',
);
// Test file creation
final testFile = await service.testStorageAccess();
print('Storage test: ${testFile.success}');
print('Storage path: ${testFile.path}');# View Android logs
adb logcat | grep document_scanner
# Check permissions
adb shell pm list permissions | grep camera
# Inspect app data
adb shell run-as com.example.app ls -la /data/data/com.example.app/files# View iOS simulator logs
xcrun simctl spawn booted log stream --predicate 'process == "document_scanner"'
# Check app permissions
# Use Xcode -> Simulator -> Device -> Privacy Settings// Monitor memory during scanning
import 'package:flutter/services.dart';
void logMemoryUsage(String phase) {
final info = ProcessInfo.currentRss;
print('Memory usage at $phase: ${info / 1024 / 1024} MB');
}
// Usage
logMemoryUsage('before_scan');
// ... perform scan
logMemoryUsage('after_scan');// Profile processing pipeline
final stopwatch = Stopwatch()..start();
final result = await DocumentScannerService().scanDocument(
documentType: DocumentType.receipt,
);
stopwatch.stop();
print('Total scan time: ${stopwatch.elapsedMilliseconds}ms');import 'package:document_scanner/document_scanner.dart';
// Set up error handling
DocumentScannerService.onError.listen((error) {
print('Scanner error: ${error.message}');
print('Error type: ${error.type}');
print('Stack trace: ${error.stackTrace}');
});
// Custom error handling
try {
final result = await DocumentScannerService().scanDocument(
documentType: DocumentType.receipt,
);
if (!result.success) {
print('Scan failed: ${result.error}');
// Handle specific error types
switch (result.errorType) {
case ScanErrorType.permissionDenied:
// Handle permission error
break;
case ScanErrorType.cameraError:
// Handle camera error
break;
case ScanErrorType.processingError:
// Handle processing error
break;
}
}
} catch (e) {
print('Unexpected error: $e');
}// Enable debug mode
DocumentScannerService.setDebugMode(true);
// Custom logging
DocumentScannerService.setLogger((level, message) {
final timestamp = DateTime.now().toIso8601String();
print('[$timestamp] [$level] $message');
});// Generate test documents
final testDocument = ScannedDocument.test(
type: DocumentType.receipt,
pageCount: 3,
hasImages: true,
);
// Generate test sessions
final testSession = MultiPageScanSession.test(
documentType: DocumentType.manual,
pageCount: 5,
);// Debug widget for testing
class DebugScannerWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DocumentScannerWidget(
documentType: DocumentType.receipt,
onScanComplete: (result) {
debugPrint('Scan result: ${result.toJson()}');
},
debugMode: true, // Enable debug overlays
);
}
}# Generate coverage report
flutter test --coverage
lcov --summary coverage/lcov.info
# Generate HTML report
genhtml coverage/lcov.info -o coverage/html
open coverage/html/index.html# Static analysis
flutter analyze
# Format code
flutter format .
# Check for potential issues
dart fix --dry-run
dart fix --applyname: Test Document Scanner
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: '3.16.0'
- run: flutter pub get
- run: flutter test --coverage
- run: flutter analyze- Clean Build:
flutter clean && flutter pub get - Update Dependencies:
flutter pub upgrade - Check Flutter Version:
flutter doctor -v
- Permission Errors: Check app permissions in device settings
- Camera Issues: Test on physical device, not emulator
- Storage Issues: Verify external storage permissions
- Memory Leaks: Use Flutter DevTools memory profiler
- Slow Processing: Check image resolution and processing options
- UI Lag: Verify background processing is working
This comprehensive testing and debugging guide should help developers effectively work with and contribute to the document_scanner package.
This package is licensed under the MIT License. See the LICENSE file for details.
Copyright (c) 2025 Eros Nardi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
This package was developed using vibe-coding supervised by AI methodology. While thoroughly designed and tested, the authors make no warranties regarding the software's performance, reliability, or suitability for any particular purpose.
π Privacy Notice: This package processes documents locally on your device. No data is transmitted to external servers unless explicitly configured by the user (e.g., cloud backup features).
Workflow Example:
- Tap "Scan First Page" β Camera opens
- Scan page β Auto-processed and added to session
- Tap "Add Page" β Scan additional pages
- View thumbnail grid β Preview, reorder, or delete pages
- Tap "Done" β All pages combined into single PDF
This multi-page capability makes the package perfect for scanning complex documents like instruction manuals, contracts, reports, and multi-page receipts.