Integrating Multimodal Extraction in Flutter Apps

Extracting structured data from unstructured documents is a persistent engineering challenge. Traditional OCR pipelines often fail on complex layouts, tables, or mixed media. By leveraging multimodal models, developers can treat documents as visual inputs rather than just text streams, enabling more accurate parsing of invoices, receipts, and forms without pre-processing every line. This approach is particularly valuable in mobile environments where server-side processing adds latency and complexity.
The core strategy involves sending the document page as an image alongside a structured prompt. This method bypasses the need for fragile regex patterns or layout analysis libraries. Instead, the model interprets the visual context directly, returning JSON or key-value pairs that match the desired schema. This technique works well for both PDFs and scanned images, providing a unified solution for diverse document types.
In this guide, we explore how to implement this workflow in Flutter using the firebase_ai package. We will cover document parsing, image conversion, prompt engineering for extraction, and handling the response. The goal is to build a reliable extraction layer that handles various document types without requiring a heavy backend server. Note that while this guide discusses Gemini, the site is not affiliated with Google, and the techniques apply broadly to multimodal models.
Frequently asked questions
What is multimodal document extraction?
It is a technique where an AI model analyzes both text and visual layout of a document simultaneously. By treating a page as an image, the model understands spatial relationships between headers, tables, and text blocks, leading to higher accuracy than text-only parsing methods.
How does Gemini differ from traditional OCR?
Traditional OCR converts pixels to text sequentially, losing layout context. Gemini analyzes the entire page as a visual scene, understanding that a table cell belongs to a specific column or that a header labels a group of values. It infers structure rather than just recognizing characters, allowing for more intelligent data extraction.
Which is better for PDF extraction: text or image mode?
Image mode is superior for scanned PDFs or complex layouts with mixed fonts and tables. Text mode works for native digital PDFs but may lose formatting cues. For maximum reliability, converting pages to high-resolution images ensures consistent results across diverse document types, especially when dealing with handwritten notes or irregular designs.
What is the context window limit for PDFs?
The model supports up to 128K tokens, allowing it to process entire multi-page documents in a single request. However, sending very large images can exceed token limits or increase latency. It is often better to process pages individually for complex documents to maintain precision and reduce processing time.
How do you handle table extraction?
Prompt the model to return JSON arrays representing rows and columns. Provide a sample table structure in the prompt to guide the output format. The model can infer column headers and row values even if the table lacks clear borders, relying on visual alignment and spacing to reconstruct the data accurately.
Can it extract data from Word documents?
Yes, by converting Word documents to images or PDFs first. Tools like the archive package can extract XML from DOCX files, but sending rendered pages as images often yields more consistent results for layout-heavy documents. This avoids parsing complexities of Office formats and preserves visual fidelity.
What are common hallucination errors?
Models may invent values not present in the document, especially in low-resolution images or complex tables. To mitigate this, ask the model to return a confidence score or cite the location of each value. Verifying extracted data against the original image is recommended for critical fields to ensure accuracy.
How to reduce latency in extraction?
Pre-process images to remove noise and enhance contrast. Use lower resolution images if detail is not critical, and batch requests when possible. Caching results for identical documents also helps. The firebase_ai package handles streaming efficiently to reduce perceived wait times, improving user experience.
Step by step
- Select Document — Use file_picker to allow users to upload PDFs, images, or Office documents from their device storage. This is the first step in the extraction workflow, enabling users to choose the source file.
- Convert to Image — Convert the selected document to a high-resolution image using libraries like pdfx or archive, preserving layout. This ensures that the visual structure is maintained for the model to analyze.
- Construct Prompt — Define a JSON schema for the output and create a clear prompt instructing the model to extract specific fields. This guides the model to return structured data that is easy to parse.
- Send Request — Send the image and prompt to the API using firebase_ai, handling the response asynchronously and parsing the JSON output. This completes the extraction process and makes the data available for use.
Understanding Multimodal Document Parsing
Multimodal extraction treats a document page as a visual canvas rather than a stream of characters. Traditional OCR engines read left-to-right, top-to-bottom, often breaking when columns intersect or tables span multiple pages. By sending the page as an image, the model sees the entire layout simultaneously, understanding spatial relationships between elements like headers, footers, and tables. This visual approach captures nuances that text-only parsers miss, such as indentation levels or color-coded highlights.
This approach is particularly effective for invoices, receipts, and forms where visual cues indicate data significance. A bold font or a box around a number signals importance, which text-only parsers might miss. The model can infer that a value next to a label belongs to that label, even if the layout is irregular or non-standard. This makes it ideal for unstructured documents where rigid formatting is not guaranteed.
Visual Layout Analysis
The model analyzes spatial positioning to determine relationships between text blocks. It recognizes that text aligned vertically forms a list, while text in a grid forms a table. This visual understanding allows for more accurate extraction of nested structures without explicit formatting tags, reducing the need for post-processing logic to reassemble fragmented data.
Contextual Inference
Beyond reading text, the model infers meaning from context. If a document contains a date field labeled "Invoice Date," the model understands that the adjacent value is a date, even if the format is ambiguous. This reduces the need for strict regex patterns and allows the system to handle variations in date formats across different documents seamlessly.
- Handles mixed fonts and varying text sizes
- Recognizes tables without borders
- Understands headers and footers
Setting Up the Flutter Environment
To integrate multimodal extraction into a Flutter app, you need to manage document selection, conversion, and API calls. The file_picker package allows users to select files from their device storage, supporting PDFs, images, and Office documents. Once a file is selected, it must be converted into a format the model can process, typically an image. This ensures that the visual layout is preserved exactly as the user sees it, which is crucial for accurate extraction.
For Office documents like DOCX or PPTX, you can use the archive package to unzip the file and extract XML content. However, for consistent results, rendering the document to an image is often preferable. Libraries like pdfx can extract pages from PDFs as images, which are then encoded and sent to the model. This approach avoids the complexity of parsing XML structures and ensures that styling and layout are maintained.
Document Selection
Use file_picker to let users upload files. Handle different file types by routing them to appropriate converters. PDFs are converted to images, while Office files may be unzipped or rendered to images depending on the desired precision. This flexibility allows the app to handle a wide variety of document formats without requiring separate libraries for each type.
Image Conversion
Convert selected files to high-resolution images. For PDFs, render each page to a PNG or JPEG. For Office files, consider using a headless browser or a library to render the document to an image, ensuring that fonts and layouts are preserved accurately. High resolution is key to ensuring that small text is readable by the model.
final picker = FilePicker.platform;
final result = await picker.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf', 'docx', 'png'],
);
if (result != null) {
final file = result.files.single.path;
// Convert file to image
}
Converting Documents to Images
The first step in multimodal extraction is converting the document into a visual format. PDFs are vector-based, so rendering them to images ensures that the model sees the same visual representation as the user. Use libraries like pdfx to extract pages and convert them to ByteData, which can then be encoded as base64 strings for API transmission. This process preserves the exact visual appearance, including fonts and spacing.
For Office documents, the process is more complex. DOCX files are ZIP archives containing XML. You can extract the XML and parse it, but this often loses visual formatting. A better approach is to render the document to an image using a library like docx_render or by sending the file to a conversion service. This preserves the layout, tables, and styling that the model relies on for accurate extraction, ensuring that the visual context is not lost.
PDF to Image Conversion
Use pdfx to load the PDF and render each page to a ByteData object. Encode this data as a base64 string, ensuring that the image quality is high enough for the model to read small text clearly. Aim for a resolution of at least 150 DPI for optimal results, balancing clarity with file size and token usage.
Office Document Rendering
For DOCX or PPTX, use the archive package to unzip the file. Extract the XML content and parse it, or use a rendering library to convert the document to an image. Rendering to an image is often more reliable for preserving layout and styling, as it captures the visual intent of the document creator.
- Maintain high resolution for clarity
- Preserve font styles and colors
- Ensure tables are visually intact
final pdf = await Pdfx.openInputFile(path: file);
final page = await pdf.getPage(1);
final image = await page.render(width: 800, height: 1200);
final bytes = image.bytes;
final base64Image = base64Encode(bytes);Prompt Engineering for Extraction
Effective extraction relies on clear, structured prompts. Define the output format explicitly, such as JSON, to make parsing the response easier. Include examples of the desired output in the prompt to guide the model. For instance, if extracting invoice data, specify fields like "invoice_number," "date," and "total_amount," and provide a sample JSON structure. This reduces ambiguity and ensures that the model returns data in a usable format.
Use system prompts to set the model's behavior. Instruct the model to act as a data extraction engine, focusing on accuracy and consistency. Avoid open-ended questions; instead, ask for specific fields. If the document contains multiple tables, specify which table to extract from or ask for all tables in a structured format. This precision helps in getting consistent results across different document types.
Structured Output Format
Define a JSON schema for the output. Specify required fields and their data types. This ensures that the response is machine-readable and can be directly used in your app without additional parsing logic. Example: {"invoice_number": "string", "total": "float"}. This structure simplifies downstream processing and integration with other systems.
Contextual Instructions
Provide instructions on how to handle missing data. Ask the model to return null or a specific placeholder if a field is not found. This prevents the model from inventing values. Also, specify how to handle ambiguous data, such as rounding decimals or formatting dates, to ensure consistency in the extracted data.
{
"invoice_number": "INV-12345",
"date": "2023-10-01",
"total": 150.00,
"items": [
{"name": "Service A", "price": 100.00},
{"name": "Service B", "price": 50.00}
]
}
Implementing the API Call
Once the document is converted to an image and the prompt is prepared, send the request to the API. Use the firebase_ai package to interact with the model. Pass the image as a part of the message content, along with the text prompt. The package handles the encoding and transmission of the multimodal request, making it easy to integrate into your Flutter app. This seamless integration allows for real-time extraction as users upload documents.
Handle the response asynchronously. The model will return a text response, which you need to parse into the defined JSON structure. Implement error handling for cases where the model fails to extract data or returns malformed JSON. You may need to retry the request with a modified prompt if the initial extraction is inaccurate. This robust handling ensures that the app remains responsive and reliable even in edge cases.
Sending the Request
Construct a message object containing the image and the text prompt. Use the firebase_ai client to send this message to the model. Ensure that the image is encoded correctly and that the prompt is clear and concise to avoid confusion. Proper encoding is crucial to prevent data loss or corruption during transmission.
Parsing the Response
Parse the model's response into the defined JSON structure. Use a JSON parser to convert the string response into a dart object. Handle any parsing errors gracefully, logging them for debugging. If the response is not valid JSON, consider asking the model to reformat the output. This iterative approach improves accuracy over time.
- Encode image as base64
- Define clear JSON schema
- Handle parsing errors
final content = [
Content.text('Extract the following fields: invoice_number, date, total.'),
Content.image(Uri.parse('data:image/png;base64,$base64Image'))
];
final response = await model.generateContent(content);
final text = response.text;
final data = jsonDecode(text);Handling Errors and Retries
Extraction is not always perfect. The model may miss a field, misinterpret a value, or return malformed JSON. Implement retry logic to handle these cases. If the response is not valid JSON, ask the model to reformat the output. If a specific field is missing, you can send a follow-up request asking for that field specifically. This targeted approach reduces token usage and improves efficiency.
Log errors and responses for debugging. This helps in identifying patterns in failures, such as specific document types or layouts that cause issues. Use this data to refine your prompts or adjust the image resolution. Consistent logging also helps in monitoring the accuracy of your extraction pipeline over time, allowing for continuous improvement of the system.
JSON Parsing Errors
If the response is not valid JSON, send a follow-up request asking the model to return valid JSON. Include the original prompt and image in the follow-up request to provide context. This can help the model correct its output format without losing the extracted data, ensuring that the final result is usable.
Field Missing Errors
If a specific field is missing, send a targeted request asking for that field. This reduces the token usage and focuses the model's attention on the missing data. It is more efficient than re-processing the entire document for a single missing value, saving both time and computational resources.
try {
final data = jsonDecode(text);
return data;
} catch (e) {
// Retry with a new prompt asking for JSON
final retryContent = [
Content.text('Return the extracted data as valid JSON.'),
Content.image(Uri.parse('data:image/png;base64,$base64Image'))
];
final retryResponse = await model.generateContent(retryContent);
return jsonDecode(retryResponse.text);
}
Optimizing Performance and Cost
Processing high-resolution images can be expensive and slow. Optimize image size by reducing resolution or compressing the image before sending it to the model. A resolution of 150 DPI is often sufficient for text extraction, balancing quality and cost. Smaller images also reduce token usage, lowering the cost per request. This optimization is crucial for apps that process a high volume of documents daily.
Caching results for identical documents is another effective strategy. If a user uploads the same PDF multiple times, store the extracted data and return it from the cache instead of re-processing. This reduces latency and cost, especially for frequently accessed documents like invoices or receipts. Implement a hash-based caching system to identify duplicate documents efficiently.
Image Resolution Tuning
Test different resolutions to find the optimal balance between accuracy and cost. Lower resolutions may reduce accuracy for small text, while higher resolutions increase token usage. Aim for a resolution that preserves readability without excessive detail, ensuring that the model can extract data accurately without unnecessary overhead.
Caching Strategies
Implement a caching layer to store extracted data for identical documents. Use a hash of the document content to identify duplicates. Cache both the raw image and the extracted JSON to avoid re-processing. This is especially useful for recurring documents like monthly invoices, where the content remains constant over time.
- Use 150 DPI for text extraction
- Compress images before upload
- Cache results for duplicates
final hash = sha256.convert(bytes).toString();
if (cache.containsKey(hash)) {
return cache[hash];
}
final result = await extractData(bytes);
cache[hash] = result;
return result;Real-World Use Cases
Multimodal extraction is widely used in finance, healthcare, and logistics. In finance, it automates invoice processing by extracting vendor details, amounts, and dates. In healthcare, it extracts patient data from scanned forms, reducing manual entry errors. In logistics, it reads shipping labels and tracking numbers, streamlining package handling. These use cases benefit from the model's ability to handle diverse document formats and layouts.
These use cases benefit from the model's ability to handle diverse document formats and layouts. Whether it is a handwritten form or a complex table, the model can adapt to the visual structure. This flexibility makes it a powerful tool for automating document-heavy workflows across various industries, reducing operational costs and improving efficiency. For more insights on related topics, see Why Does Gemini 3.5 Flash Hallucinate? and What Is the Fake Context Alignment Attack?.
Invoice Processing
Automate the extraction of vendor name, invoice number, date, and total amount. This reduces the time spent on manual data entry and minimizes errors. The model can handle various invoice formats, from simple receipts to complex multi-page statements, making it versatile for different business needs.
Healthcare Form Parsing
Extract patient details, diagnosis codes, and treatment plans from scanned forms. This improves data accuracy and speeds up claims processing. The model can recognize handwritten text and complex layouts, making it suitable for diverse medical documents that often have unique formatting requirements.

Test Gemini models right now with no account, no credit card, and no region lock required.