279 lines
9.7 KiB
Markdown
279 lines
9.7 KiB
Markdown
# Flutter Barcode Scanner App Expert Guidelines
|
|
|
|
## Flexibility Notice
|
|
**Important**: This is a recommended project structure, but be flexible and adapt to existing project structures. Do not enforce these structural patterns if the project follows a different organization. Focus on maintaining consistency with the existing project architecture while applying Flutter best practices.
|
|
|
|
## Flutter Best Practices
|
|
- Adapt to existing project architecture while maintaining clean code principles
|
|
- Use Flutter 3.x features and Material 3 design
|
|
- Implement clean architecture with Riverpod pattern
|
|
- Follow proper state management principles
|
|
- Use proper dependency injection
|
|
- Implement proper error handling
|
|
- Follow platform-specific design guidelines
|
|
- Use proper localization techniques
|
|
|
|
## Preferred Project Structure
|
|
**Note**: This is a reference structure. Adapt to the project's existing organization.
|
|
|
|
```
|
|
lib/
|
|
core/
|
|
constants/
|
|
theme/
|
|
utils/
|
|
widgets/
|
|
network/
|
|
api_client.dart
|
|
api_endpoints.dart
|
|
network_service.dart
|
|
features/
|
|
scanner/
|
|
data/
|
|
datasources/
|
|
scanner_remote_datasource.dart
|
|
scanner_local_datasource.dart
|
|
models/
|
|
scan_response_model.dart
|
|
barcode_data_model.dart
|
|
repositories/
|
|
scanner_repository_impl.dart
|
|
domain/
|
|
entities/
|
|
scan_entity.dart
|
|
barcode_entity.dart
|
|
repositories/
|
|
scanner_repository.dart
|
|
usecases/
|
|
get_barcode_data_usecase.dart
|
|
save_scan_usecase.dart
|
|
presentation/
|
|
providers/
|
|
scanner_provider.dart
|
|
scan_detail_provider.dart
|
|
pages/
|
|
home_page.dart
|
|
scan_detail_page.dart
|
|
widgets/
|
|
barcode_scanner_widget.dart
|
|
scan_history_list.dart
|
|
scan_form_widget.dart
|
|
loading_widget.dart
|
|
history/
|
|
data/
|
|
domain/
|
|
presentation/
|
|
l10n/
|
|
main.dart
|
|
test/
|
|
unit/
|
|
widget/
|
|
integration/
|
|
```
|
|
|
|
## App Architecture Overview
|
|
This barcode scanner app follows a two-screen flow with API integration:
|
|
1. **Home Screen**: Barcode scanner + scan history list
|
|
2. **Detail Screen**: API call → Loading → Form with 4 text fields + save/print buttons
|
|
|
|
### Key Workflows
|
|
1. **Barcode Scanning**: Open camera → Scan barcode → Navigate to detail screen
|
|
2. **API Integration**: Pass scanned value → Call API → Handle loading/error states → Populate form
|
|
3. **Form Entry**: Display API data in 4 text fields → Allow editing → Save data locally → Print functionality
|
|
4. **History Management**: View previous scans on home screen → Tap to view/edit → Re-fetch from API if needed
|
|
5. **Offline Support**: Cache API responses locally using Hive + display cached data when offline
|
|
|
|
### Important Data Concepts
|
|
- **Scan Entity**: Barcode value + timestamp + API response data + custom field data
|
|
- **API Response**: External data fetched based on barcode value
|
|
- **History List**: Chronological list of all scanned items with cached API data
|
|
- **Form Fields**: 4 text fields populated from API response (editable)
|
|
- **Network State**: Loading, success, error, offline states
|
|
|
|
## Core Features Implementation
|
|
|
|
### Barcode Scanner Integration
|
|
- Use **mobile_scanner** package for reliable scanning
|
|
- Support Code128 and other common barcode formats
|
|
- Implement proper camera permissions
|
|
- Handle scanner lifecycle (pause/resume)
|
|
- Provide visual feedback for successful scans
|
|
|
|
### API Integration Layer
|
|
- **HTTP Client**: Use Dio or http package with proper configuration
|
|
- **Base URL**: Configurable API endpoint
|
|
- **Authentication**: Handle API keys/tokens if required
|
|
- **Request/Response Models**: Proper JSON serialization
|
|
- **Timeout Handling**: Network timeout configuration
|
|
- **Retry Logic**: Implement retry for failed requests
|
|
|
|
### Local Data Storage & Caching
|
|
- Use **Hive** for fast, local database storage
|
|
- **Cache Strategy**: Store API responses with timestamps
|
|
- **Offline Mode**: Display cached data when network unavailable
|
|
- **Cache Invalidation**: Refresh expired cache entries
|
|
- **Sync Strategy**: Background sync when network restored
|
|
|
|
### Navigation Flow
|
|
- **Home → Detail**: Pass scanned barcode value + trigger API call
|
|
- **Detail Loading**: Show loading indicator during API call
|
|
- **Detail Success**: Display form with API data
|
|
- **Detail Error**: Show error message with retry option
|
|
- **Detail → Home**: Return with save confirmation
|
|
|
|
### Network State Management
|
|
- **Loading States**: Visual indicators during API calls
|
|
- **Error Handling**: Network errors, API errors, timeout errors
|
|
- **Retry Mechanism**: User-initiated and automatic retries
|
|
- **Offline Detection**: Network connectivity monitoring
|
|
|
|
## Performance Considerations
|
|
- **Scanner Performance**: Optimize camera preview and barcode detection
|
|
- **API Caching**: Cache API responses to reduce network calls
|
|
- **Hive Queries**: Efficient history list loading with pagination
|
|
- **Memory Management**: Proper disposal of camera and network resources
|
|
- **Background Sync**: Efficient background data synchronization
|
|
- **Image Loading**: Lazy load any images from API responses
|
|
|
|
## Security & Network Considerations
|
|
- **HTTPS**: Enforce secure API connections
|
|
- **API Keys**: Secure storage using flutter_secure_storage
|
|
- **Input Validation**: Sanitize barcode values before API calls
|
|
- **Certificate Pinning**: Optional for high-security requirements
|
|
- **Rate Limiting**: Respect API rate limits
|
|
- **Data Encryption**: Encrypt sensitive cached data
|
|
|
|
## Widget Guidelines
|
|
|
|
### Scanner Widget
|
|
- Implement proper camera lifecycle management
|
|
- Provide visual scan indicators
|
|
- Handle different screen orientations
|
|
- Support flashlight toggle
|
|
- Error handling for camera failures
|
|
|
|
### Detail Screen Widgets
|
|
- **Loading Widget**: Skeleton loading or progress indicators
|
|
- **Error Widget**: User-friendly error messages with retry buttons
|
|
- **Form Widget**: Pre-populated fields from API response
|
|
- **Network Status**: Visual indicators for online/offline status
|
|
|
|
### History List
|
|
- Efficient scrolling with ListView.builder
|
|
- Pull-to-refresh functionality (triggers API refresh)
|
|
- Search/filter capabilities
|
|
- Swipe-to-delete actions
|
|
- Visual indicators for cached vs fresh data
|
|
- Export options
|
|
|
|
## Common Patterns for This App
|
|
|
|
### State Management with Riverpod
|
|
```dart
|
|
// Scanner state
|
|
final scannerStateProvider = StateNotifierProvider<ScannerNotifier, ScannerState>
|
|
|
|
// API call state
|
|
final barcodeDataProvider = FutureProvider.family<BarcodeData, String>((ref, barcode) async {
|
|
return ref.read(scannerRepositoryProvider).getBarcodeData(barcode);
|
|
});
|
|
|
|
// History state with cached API data
|
|
final historyProvider = StateNotifierProvider<HistoryNotifier, List<ScanEntity>>
|
|
|
|
// Form state with API pre-population
|
|
final formProvider = StateNotifierProvider<FormNotifier, FormState>
|
|
|
|
// Network connectivity
|
|
final connectivityProvider = StreamProvider<ConnectivityResult>
|
|
```
|
|
|
|
### API Error Handling
|
|
```dart
|
|
sealed class ApiResult<T> {
|
|
const ApiResult();
|
|
}
|
|
|
|
class ApiSuccess<T> extends ApiResult<T> {
|
|
final T data;
|
|
const ApiSuccess(this.data);
|
|
}
|
|
|
|
class ApiError<T> extends ApiResult<T> {
|
|
final String message;
|
|
final int? statusCode;
|
|
const ApiError(this.message, this.statusCode);
|
|
}
|
|
|
|
class ApiLoading<T> extends ApiResult<T> {
|
|
const ApiLoading();
|
|
}
|
|
```
|
|
|
|
### Repository Pattern with Caching
|
|
```dart
|
|
abstract class ScannerRepository {
|
|
Future<Either<Failure, BarcodeData>> getBarcodeData(String barcode);
|
|
Future<Either<Failure, void>> saveScanData(ScanEntity scan);
|
|
}
|
|
|
|
class ScannerRepositoryImpl implements ScannerRepository {
|
|
final ScannerRemoteDataSource remoteDataSource;
|
|
final ScannerLocalDataSource localDataSource;
|
|
final NetworkInfo networkInfo;
|
|
|
|
// Implementation with cache-first or network-first strategies
|
|
}
|
|
```
|
|
|
|
## Testing Guidelines
|
|
1. **API Tests**: Mock HTTP responses and error scenarios
|
|
2. **Repository Tests**: Test caching and offline behavior
|
|
3. **Scanner Tests**: Mock barcode scanning scenarios
|
|
4. **Hive Tests**: Database CRUD operations
|
|
5. **Form Tests**: Validation and data persistence with API data
|
|
6. **Navigation Tests**: Screen transitions with API loading states
|
|
7. **Network Tests**: Connectivity changes and retry logic
|
|
8. **Integration Tests**: Complete user workflows including API calls
|
|
|
|
## Error Handling Scenarios
|
|
- **Network Errors**: No internet connection, timeout, server unavailable
|
|
- **API Errors**: Invalid barcode, 404 not found, 500 server error, rate limiting
|
|
- **Scanner Errors**: Camera permission denied, scanning failures
|
|
- **Storage Errors**: Hive database errors, disk space issues
|
|
- **Validation Errors**: Invalid form data, missing required fields
|
|
|
|
## Platform-Specific Considerations
|
|
|
|
### Android
|
|
- Network security configuration
|
|
- Background sync limitations
|
|
- Proper hardware acceleration
|
|
- Print service integration
|
|
|
|
### iOS
|
|
- App Transport Security (ATS) settings
|
|
- Network permissions and privacy
|
|
- Background app refresh policies
|
|
- AirPrint integration
|
|
|
|
## Coding Guidelines
|
|
1. Use proper null safety practices
|
|
2. Implement proper error handling with Either type
|
|
3. Follow proper naming conventions
|
|
4. Use proper widget composition
|
|
5. Implement proper routing using GoRouter
|
|
6. Use proper form validation
|
|
7. Follow proper state management with Riverpod
|
|
8. Implement proper dependency injection using GetIt
|
|
9. Use proper asset management
|
|
|
|
## Refactoring Instructions
|
|
When refactoring code:
|
|
- Always maintain existing project structure patterns
|
|
- Prioritize consistency with current codebase
|
|
- Apply Flutter best practices without breaking existing architecture
|
|
- Focus on incremental improvements
|
|
- Ensure all changes maintain backward compatibility
|
|
|
|
This architecture ensures a robust, maintainable barcode scanning application with reliable API integration and offline capabilities. |