form_gear_engine_sdk 0.17.0
form_gear_engine_sdk: ^0.17.0 copied to clipboard
Flutter SDK for FormGear - A flexible, JSON-driven form generation framework for dynamic data collection with 30+ input control types, nested forms, GPS, photo capture, and complex validation capabilities.
FormGear Flutter SDK #
A flexible, JSON-driven form generation framework for dynamic data collection
A Flutter SDK for FormGear - A flexible, JSON-driven form generation framework for dynamic data collection, originally developed for BPS - Statistics Indonesia's FASIH App.
Features #
- 🎯 JSON-driven forms with 30+ input control types
- 📱 Multi-engine support: FormGear (ID 1) and FasihForm (ID 2)
- 📷 Device integration: Camera, GPS, file uploads, signature capture
- 🔒 Security: Input validation, HTTPS enforcement, log sanitization
- 💾 Offline capability: Forms work without internet
- 🎨 Customizable listeners: SaveOrSubmit and FileUpload patterns
Installation #
dependencies:
form_gear_engine_sdk: ^0.4.0
Platform Setup #
Android - Add to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
iOS - Add to Info.plist:
<key>NSCameraUsageDescription</key>
<string>Camera access for form photos</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location access for GPS coordinates</string>
Quick Start #
1. Initialize SDK #
import 'package:form_gear_engine_sdk/form_gear_engine_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Configure API
final apiConfig = FormGearApiConfig(
baseUrl: 'https://your-api.com',
formEngineEndpoint: '/api/form-engine/version',
authToken: 'your-token',
);
// Initialize SDK
final config = FormGearConfig(
autoStartServer: true,
serverPort: 8080,
apiConfig: apiConfig,
bpsUser: BpsUser(
sessionToken: 'user-token',
nipBaru: '123456789',
),
);
await FormGearSDK.instance.initialize(config);
runApp(MyApp());
}
2. Open a Form with Assignment #
class FormPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
// Create assignment context
final assignment = AssignmentContext(
assignmentId: 'assignment_001',
templateId: 'demo_template',
surveyId: 'survey_2024',
config: AssignmentConfig(
lookupMode: FormGearLookupMode.offline,
formMode: FormGearFormMode.open,
clientMode: FormGearClientMode.capi,
),
data: AssignmentData(
template: {/* template data */},
validation: {/* validation rules */},
response: {/* form responses */},
),
);
// Open form with assignment
await FormGearSDK.instance.openFormWithAssignment(
context: context,
assignment: assignment,
title: 'Survey Form',
);
},
child: Text('Open Form'),
);
}
}
3. Check Engine Version #
// Check if engine update is needed
final result = await FormGearSDK.instance.checkFormEngineVersion(
context: context,
engineId: '1',
);
if (result != null) {
print('Current version: ${result.currentVersion}');
print('Latest version: ${result.latestVersion}');
print('Update available: ${result.updateAvailable}');
}
4. Check if Engine is Downloaded #
// Check if engine exists locally
final isDownloaded = await FormGearSDK.instance.isFormEngineDownloaded('1');
if (!isDownloaded) {
// Show download screen or prompt
}
5. Custom Update UI #
By default, checkFormEngineVersion shows the SDK's own update screen when
the engine is missing or outdated. To draw your own UI, register a
FormEngineUpdateHandler. The SDK then calls it instead, including for
forced updates (result.isForced), which must not be dismissible.
class MyUpdateHandler implements FormEngineUpdateHandler {
@override
Future<void> onUpdateRequired(
BuildContext context,
VersionCheckResult result,
FormEngineDownloader download,
) async {
// Show your own sheet or page here, then:
final outcome = await download(
onProgress: (percent) => print('$percent%'), // 0-100
);
outcome.fold(
(error) => print('Download failed: $error'), // an AppFailure
(_) => print('Engine ready'),
);
}
}
FormGearSDK.instance.formEngineUpdateHandler = MyUpdateHandler();
Without a handler, nothing changes. To download with no UI at all, call
FormGearSDK.instance.downloadFormEngine('1', onProgress: ...). It returns
a Result<void>.
Public API Reference #
FormGearSDK #
Main SDK entry point.
Methods
| Method | Description |
|---|---|
initialize(FormGearConfig config) |
Initialize SDK with configuration |
openFormWithAssignment({BuildContext, AssignmentContext, ...}) |
Primary API - Open form with assignment context |
checkFormEngineVersion({BuildContext? context, String? engineId}) |
Check for engine updates |
isFormEngineDownloaded(String engineId) |
Check if engine exists locally |
downloadFormEngine(String engineId, {onProgress}) |
Download and install an engine with no UI |
formEngineUpdateHandler |
Property: host UI for engine downloads and updates |
setFormDataListener(FormDataListener listener) |
Register save/submit listener |
setFileUploadListener(FileUploadListener listener) |
Register file upload listener |
removeFormDataListener() |
Remove save/submit listener |
removeFileUploadListener() |
Remove file upload listener |
Configuration Models #
FormGearConfig
FormGearConfig({
bool autoStartServer = true,
int serverPort = 8080,
bool enableLogging = false,
FormGearApiConfig? apiConfig,
BpsUser? bpsUser,
FormGearClientMode clientMode = FormGearClientMode.capi,
FormGearLookupMode lookupMode = FormGearLookupMode.offline,
FormGearFormMode formMode = FormGearFormMode.open,
})
FormGearApiConfig
FormGearApiConfig({
String? baseUrl,
String? formEngineEndpoint,
String? authToken,
Map<String, String> customHeaders = const {},
bool isProduction = true,
Map<String, List<String>>? pinnedCertificates, // For SSL pinning
})
BpsUser
BpsUser({
String? sessionToken,
String? authToken,
String? nipBaru,
String? nama,
String? jabatan,
String? org,
// ... other fields
})
Enums #
FormGearClientMode
capi- Computer Assisted Personal Interviewingcawi- Computer Assisted Web Interviewing
FormGearLookupMode
online- Fetch lookup data from serveroffline- Use cached lookup datalocal- Use local lookup data
FormGearFormMode
open- Form is editablesubmitted- Form is read-only (submitted)rejected- Form was rejected (editable)
SaveOrSubmit Listener #
Handle form save/submit operations with custom logic.
class MyFormDataListener extends FormDataListener {
@override
Future<SaveSubmitResult> onSaveOrSubmit(SaveSubmitData data) async {
// Handle FormGear save/submit
await myDatabase.save(data);
return SaveSubmitResult.success(submissionId: 'form_${data.assignmentId}');
}
@override
Future<SaveSubmitResult> onSaveOrSubmitFasihForm(SaveSubmitData data) async {
// Handle FasihForm save/submit
await myDatabase.saveFasih(data);
return SaveSubmitResult.success(submissionId: 'fasih_${data.assignmentId}');
}
}
// Register listener
FormGearSDK.instance.setFormDataListener(MyFormDataListener());
SaveSubmitData
class SaveSubmitData {
final String assignmentId;
final String templateId;
final String surveyId;
final Map<String, dynamic> formData;
final Map<String, dynamic> remark;
final List<dynamic> principal;
final Map<String, dynamic>? reference; // FormGear only
final Map<String, dynamic>? media; // FormGear only
final String flag; // 'save' or 'submit'
}
SaveSubmitResult
// Success
SaveSubmitResult.success(submissionId: 'abc123')
// Failure
SaveSubmitResult.failure(error: 'Database error')
FileUpload Listener #
Handle file uploads with custom backend integration.
class MyFileUploadListener implements FileUploadListener {
@override
Future<FileUploadResult> onFileUpload(FileUploadData data) async {
// Upload to your backend (S3, server, etc.)
final url = await uploadToBackend(data.file, data.fileName);
return FileUploadResult.success(uploadedUrl: url);
}
@override
void onUploadProgress(String fileName, int sent, int total) {
print('Upload: ${(sent / total * 100).toInt()}%');
}
}
// Register listener
FormGearSDK.instance.setFileUploadListener(MyFileUploadListener());
FileUploadData
class FileUploadData {
final String assignmentId;
final String templateId;
final String dataKey;
final File file;
final String fileName;
final String fileUri;
final Map<String, dynamic>? metadata;
}
FileUploadResult
// Success
FileUploadResult.success(uploadedUrl: 'https://s3.amazonaws.com/...')
// Failure
FileUploadResult.failure(error: 'Upload failed')
Result Pattern #
Type-safe error handling for SDK operations.
final result = await checkFormEngineVersionUseCase();
result.fold(
onFailure: (error) {
print('Error: $error');
},
onSuccess: (response) {
print('Version: ${response.version}');
},
);
Result Types
sealed class Result<T> {}
class Success<T> extends Result<T> {
final T data;
}
class Failure<T> extends Result<T> {
final Object error;
final StackTrace? stackTrace;
}
Models #
FormEngineEntity
class FormEngineEntity {
final String id; // '1' or '2'
final String name; // Engine name
final String version; // Version number
final String? linkDownload; // Download URL
final String? description;
}
VersionCheckResult
class VersionCheckResult {
final FormEngineEntity engine;
final String? currentVersion;
final String? latestVersion;
final bool updateAvailable;
final VersionState state; // upToDate, updateAvailable, notInstalled
}
Host UI, edge-to-edge and bridge events #
Extend FormGearUiHandler and set FormGearSDK.instance.uiHandler to draw the
loader, the load error, the exit dialog and the version-check error in your
own design system. Each method returns null (or false) to keep the built-in
UI. The form page draws edge to edge by default; return false from
edgeToEdge to opt out. The web view sits inside the safe area; return
false from useSafeArea to let it fill the page (the insets reach the engine
as the CSS variables --safe-area-inset-top|right|bottom|left; the SDK also
pads the engine's mount element (#fasih-form) with them, so the header clears
the status bar and the footer clears the gesture bar). Override processCapturedPhoto to change a fresh camera photo before the SDK saves it (for example a time and place stamp; gallery picks skip it). Override onMockLocation to warn, or close the form, when a position comes from a mock provider (fake GPS); the position is still given to the form. FormGearSDK.instance.bridgeEvents streams every JS
bridge event for debuggers. See docs/adr/0001-host-ui-handler-and-bridge-events.md.
Barcode and QR scanning #
The SDK has no scanner of its own (it used to ship a zxing screen; that code
and the flutter_zxing dependency are gone, so a host that scans owns the
camera screen and its size). The BARCODE and QR_SCAN form actions call
FormGearUiHandler.scanBarcode(context, request). Open your scanner there and
return the code:
class MyHandler extends FormGearUiHandler {
@override
Future<BarcodeScanResult?> scanBarcode(
BuildContext context,
BarcodeScanRequest request,
) async {
final code = await myScanner(context); // your camera screen
return code == null
? const BarcodeScanResult.cancelled()
: BarcodeScanResult(text: code.text, format: code.format);
}
}
The default returns null, and the form then shows that scanning is not
available. Migration from 0.11 to 0.13: BarcodeScannerEngine,
ScannedCode, ScannerPermissionDenied and FormGearScanner.engineBuilder
are removed; move your engine into the scanBarcode screen.
Host capabilities (0.15) #
Device features come from the host through one class, FormGearCapabilities,
set with FormGearSDK.instance.capabilities = MyCapabilities(). Every member
defaults to "not provided". Phase 2 covers capturePhoto, pickFile and
scan:
class MyCapabilities extends FormGearCapabilities {
@override
CapabilitySupport support(CapabilityKind kind) => switch (kind) {
CapabilityKind.photo || CapabilityKind.pickFile =>
const CapabilitySupport.supported(),
_ => const CapabilitySupport.unsupported(),
};
@override
Future<CapturedMedia?> capturePhoto(CapturePhotoRequest r) async {
final file = await myCamera(r.context); // your UI and permissions
return file == null ? null : CapturedMedia(file: file); // null = cancelled
}
}
null means the user cancelled; a failure is a CapabilityException with a
sentence for the user. The engine still names the file, stores it in the
assignment media folder and updates media.json. All three bridge routes
(action, execute and the client handlers) use the same call. While the SDK
is 0.x, a kind the host does not provide keeps the built-in camera and picker
(image_picker, file_picker); they go away in 1.0.0.
FormGearUiHandler.scanBarcode is deprecated and forwards to
FormGearCapabilities.scan (same types).
Removed APIs #
The following internal APIs have been removed from the public surface:
FormGearDownloadManager- Use bundled assets or implement custom download- Template download methods - Manage templates in your app
- Update screens - Implement custom UI for updates
Changed APIs #
FormGearApiConfignow only requiresformEngineEndpoint(version check)- All form operations through
FormGearSDK.instancemethods - Listeners are now the recommended way to handle save/submit and uploads
Contributing #
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License #
MIT License - see LICENSE file for details.
Support #
Made with ❤️ for FASIH App and the Flutter community