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 through your app: camera, audio, video, scan, file pick and GPS come from
FormGearCapabilities; the SDK ships no device plugin - 🔒 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: ^1.0.0
Platform Setup
The SDK needs only the network for its web view.
Android - AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Camera, microphone, location and photo permissions belong to your app, because your app provides those capabilities. See the checklist in MIGRATION.md.
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 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.
Host capabilities (FormGearCapabilities)
The SDK owns the web view, the local server, the bridge, the data and the engine download. Everything that touches the device comes from your app, through one class. Set it once:
FormGearSDK.instance.capabilities = MyCapabilities();
Extend the class (do not implement it), so members added later keep their defaults. Every member defaults to "not provided".
| Member | Kind | What the host does |
|---|---|---|
capturePhoto(CapturePhotoRequest) |
photo |
Take one photo (camera, stamp, resize) |
pickFile(PickRequest) |
pickFile |
Pick one file or gallery image |
scan(BuildContext, BarcodeScanRequest) |
scan |
Scan one barcode or QR code |
recordAudio(RecordAudioRequest) |
audio |
Record one clip, with its own sheet |
recordVideo(RecordVideoRequest) |
video |
Record one clip, with its own page |
locate(LocateRequest) |
locate |
Get one position, flag mock GPS |
support(CapabilityKind) |
all | Say which of the above you do |
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
}
}
Rules:
nullmeans the user cancelled. It is not an error.- A failure is a
CapabilityExceptionwith a sentence for the user. UseCapabilityException.deniedfor a refused permission. - The host asks for its own permissions.
- The engine names the final file, stores it in the assignment media folder and
updates
media.json. - The form closing fires
request.cancel, so you can pop your route. - A kind you do not provide gives the form
Fitur ini belum tersedia di aplikasi("tidak tersedia"). Nothing opens and nothing crashes.
All bridge routes (action, execute and the client handlers) go through one
CapabilityBroker, so a capability behaves the same on every route. A fix with
LocationFix.isMock == true calls FormGearUiHandler.onMockLocation; the fix
is still returned.
Upgrading from 0.x? Follow MIGRATION.md.
Run the example
cd example
flutter pub get
flutter run
The example uses stub capabilities (example/lib/example_capabilities.dart): a
sample photo, a sample CSV file, a fixed position and a dialog for scans. Audio
and video are left out on purpose, so you can see the "tidak tersedia" reply.
The example needs an .env for its API settings (see example/lib/env/env.dart).
Versions and deprecation
- 0.14 to 0.17 added one capability each and kept a deprecated built-in fallback.
- 1.0.0 removed the fallbacks, the plugins and the built-in screens.
- From 1.0.0 the SDK follows semantic versioning. A new capability is a minor release and defaults to "not provided". A removal is a major release, with a deprecation window of at least two minor releases first.
What is next
- Engine registry: engines 1 and 2 are the only ones the SDK knows today. A planned registry (open engine keys, a signed feed, per-survey selection) will let a host run another engine. This is a plan, not a feature yet. See the capabilities epic.
- Host bridge: a platform-agnostic bridge to replace
window.Androidis in RFC. See issue #96.
Tracking: capabilities epic #110 and phase 5 #101.
Removed APIs
See the full list in MIGRATION.md. Earlier removals 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