instantdb_flutter 0.2.6
instantdb_flutter: ^0.2.6 copied to clipboard
A real-time, offline-first database client for Flutter with reactive bindings.
0.2.6 #
π― New Feature: Session Token Access API #
Added Session Token Access
- β
Added
sessionTokengetter - Preferred name for accessing the current user's session token - β
Added
getSessionToken()method - Method-based access for those who prefer method calls - β Enhanced API clarity - Clear naming for use in API authentication headers
- β
Full backward compatibility - Existing
authTokengetter continues to work unchanged
Use Cases
- β
API authentication - Use session token in
Authorization: Bearer <token>headers - β Proxy authentication - Pass token to Cloudflare Workers or other proxies for user validation
- β Cost tracking - Track API usage per user by validating tokens server-side
API Examples
// Getter-based access (preferred)
final token = db.auth.sessionToken;
if (token != null) {
headers['Authorization'] = 'Bearer $token';
}
// Method-based access
final token = db.auth.getSessionToken();
if (token != null) {
headers['Authorization'] = 'Bearer $token';
}
// Backward compatible - existing code still works
final token = db.auth.authToken; // Still available
Technical Details
- β
Same underlying token - All three methods (
sessionToken,getSessionToken(),authToken) return the same JWT token - β
Null when not authenticated - Returns
nullwhen user is not signed in - β Comprehensive test coverage - Added 7 new tests for session token access
π Impact #
This release addresses a common user request for accessing the session token for use in API authentication. The new API provides clearer naming while maintaining full backward compatibility with the existing authToken getter.
0.2.5 #
π― API Enhancement: Documents Getter for Better Developer Experience #
Added Convenience API
- β
Added
documentsgetter to QueryResult - Provides direct access to query results using familiar API pattern - β
Enhanced developer experience - Developers can now use
result.documents.lengthas expected - β
Backward compatibility - Existing
result.data?['collection']API continues to work unchanged - β Smart collection detection - Automatically returns documents from the first collection in query result
Technical Implementation
- β First collection fallback - Returns documents from the first collection when multiple collections exist
- β Safe empty list handling - Returns empty list for loading, error, or null data states
- β
Type safety - Ensures all returned items are properly typed as
Map<String, dynamic>
π Impact #
This release solves an API discrepancy where developers expected a documents field on QueryResult but had to use the more verbose result.data?['collection'] pattern. Now both approaches work:
New convenient API:
final result = db.query({'conversations': {}}).value;
print('Returned ${result.documents.length} documents');
Existing API (still works):
final conversations = result.data?['conversations'] as List? ?? [];
print('Returned ${conversations.length} conversations');
0.2.4 #
π― Critical Fix: Entity Type Resolution in Datalog Conversion #
Fixed Entity Type Mismatch Bug
- β Fixed entities being cached under wrong collection name - Queries for 'conversations' no longer return 0 documents when entities lack __type field
- β
Proper entity type detection - Extract query entity type from response
data['q']field and use it throughout conversion pipeline - β Correct cache key resolution - Entities are now cached under their query type instead of defaulting to 'todos'
Technical Solution
- β Query type extraction - Parse the original query from response to determine intended entity type
- β Type propagation - Pass entity type through entire datalog conversion pipeline
- β Smart grouping - Use query type when grouping entities, fallback to __type field, then 'todos'
- β Cache alignment - Ensure cached collection names match query collection names
π Impact #
This release completes the datalog conversion fix trilogy. The critical bug was:
- App queries for
{'conversations': {}} - Server returns datalog with conversation entities
- Entities lack __type field, so they default to 'todos'
- Cache stores them under 'todos' key
- Query engine looks for 'conversations' and finds nothing
Now fixed: Entities are cached under the correct collection name matching the original query.
0.2.3 #
π₯ Critical Fix: Race Condition in Query Execution #
Fixed Critical Race Condition
- β Fixed queries returning 0 documents despite successful datalog conversion - Eliminated race condition where queries returned empty results before cache was populated
- β Synchronous cache checking - Queries now check cache synchronously before returning Signal, ensuring immediate data availability
- β Added "Reconstructed X entities" logging - Clear logging confirms entities are successfully parsed from join-rows
Technical Improvements
- β Synchronous initialization - Query Signals are now initialized with cached data if available, preventing empty initial results
- β Enhanced logging pipeline - Added comprehensive logging throughout datalog conversion: parsing, reconstruction, grouping, and caching
- β Immediate data availability - Applications receive data immediately when cache is populated, no async delays
π Impact #
This release fixes the final piece of the datalog conversion issue. While v0.2.2 added caching, there was still a race condition causing queries to return empty results. Now:
- Cache is checked synchronously BEFORE creating the query Signal
- Query results are initialized with cached data immediately
- Applications receive data without any race conditions
- Full visibility into datalog processing with enhanced logging
The complete fix ensures: No more "0 documents" when data exists. The package now properly converts datalog, caches it, AND returns it immediately to applications.
0.2.2 #
π Major Fix: Query Result Caching for Datalog Format #
Fixed Critical Issue
- β Fixed datalog format not being returned as collection format - Applications now receive properly converted collection data instead of raw datalog format
- β Added query result caching - Converted datalog results are cached for immediate access, solving the "0 documents" issue
- β Improved data availability - Queries now return cached results immediately after datalog conversion, without waiting for async storage operations
Technical Improvements
- β Query result cache in SyncEngine - Stores converted collection data from datalog processing
- β Cache-first query strategy - QueryEngine checks cache before querying storage
- β Smart cache invalidation - Cache clears when local transactions affect collections
- β Enhanced query filtering - Apply where, orderBy, limit, and offset to cached data
Architecture Enhancements
- β Direct data path - Datalog conversion results are immediately available to queries
- β Reduced latency - No dependency on async storage operations for query results
- β Better synchronization - Ensures data consistency between datalog processing and query results
π Impact #
This release fixes a critical issue where applications using the InstantDB Flutter package would receive 0 documents from queries, even though the package successfully processed datalog internally. The fix ensures that:
- Datalog format is properly converted to collection format
- Converted data is immediately available to applications
- No data loss occurs during the conversion process
- Applications no longer need workarounds to parse datalog manually
For AppShell Users: While AppShell v0.7.19+ includes a workaround, updating to InstantDB Flutter v0.2.2 provides the proper fix at the package level.
0.2.1 #
π Critical Bug Fixes #
Enhanced Datalog Processing
- β Fixed datalog-result format edge cases - Resolved scenarios where malformed join-rows or unexpected data structures could cause silent failures, leading to empty query results despite data existing in the response
- β Added robust format detection - Implemented comprehensive datalog format detection that handles multiple variations including nested structures and different datalog path locations
- β Enhanced error logging - Added detailed logging for unrecognized query response formats to aid debugging instead of failing silently
- β Multiple fallback paths - Added systematic fallback logic that tries various datalog extraction methods before falling back to simple collection format
- β Improved delete detection - Better handling of entity deletions across different data formats and connection states
Connection & Timing Improvements
- β Fixed connection timing race conditions - Resolved timing-dependent format detection failures during connection initialization that could cause datalog responses to be ignored
- β
Enhanced message type handling - Improved processing of different query response message types (
add-query-ok,refresh-ok,query-invalidation) with varying data structure expectations - β Added explicit failure warnings - Replaced silent failures with explicit warnings when query responses don't match expected formats
π§ Technical Improvements #
Code Quality
- β Modularized datalog processing - Refactored datalog handling into focused, testable methods for better maintainability
- β Enhanced type safety - Improved type checking and reduced unnecessary casts in datalog processing logic
- β Better error reporting - Added comprehensive logging at different levels to help debug datalog processing issues
Architecture
- β Robust conversion pipeline - Implemented a systematic approach to converting datalog-result format to collection format with multiple validation points
- β Improved data flow - Enhanced the data processing pipeline to handle edge cases gracefully while maintaining performance
π Documentation #
- β Updated CLAUDE.md with detailed information about datalog processing improvements
- β Added documentation for debugging datalog format detection issues
0.2.0 #
π Major Features - React/JS SDK Feature Parity #
New Transaction System (tx namespace)
- β
Added fluent
txnamespace API for cleaner transactions (db.tx['entity'][id].update({})) - β
Implemented
transactChunk()method for transaction chunks - β
Added
merge()operation for deep nested object updates - β
Added
link()andunlink()operations for entity relationships - β
Implemented
lookup()references to reference entities by attributes instead of IDs
Advanced Query Operators
- β
Added comparison operators:
$gt,$gte,$lt,$lte,$ne - β
Added string pattern matching:
$like,$ilikewith wildcard support - β
Added array operations:
$contains,$size,$in,$nin - β
Added existence operators:
$exists,$isNull - β
Enhanced logical operators: improved
$and,$or,$notsupport
Room-based Presence System
- β
Added
joinRoom()API returning scopedInstantRoominstances - β Implemented room-specific presence operations (scoped to individual rooms)
- β
Added topic-based pub/sub messaging with
publishTopic()andsubscribeTopic() - β Complete room isolation - presence data separated between rooms
- β Backward compatible with existing direct room ID APIs
API Improvements
- β
Added
subscribeQuery()alias for reactive queries (matches React SDK) - β
Implemented
queryOnce()for one-time query execution - β
Added
getAuth()andsubscribeAuth()convenience methods - β Improved error handling and validation
π§ͺ Testing & Quality #
- β 150 total tests passing (up from 118 tests)
- β Added comprehensive test suite for all new features
- β Performance testing for large datasets and query caching
- β Room-based presence system testing with isolation validation
π Bug Fixes & Performance Improvements #
- β Fixed transaction conversion for real-time sync - transactions now properly convert to tx-steps with actual data instead of sending 0 steps
- β Fixed duplicate entity issue during sync - implemented deduplication logic to prevent locally-created entities from being re-applied during refresh-ok
- β
Fixed entity type resolution during sync - entities from server now properly stored with correct type (e.g.,
todos:idinstead ofunknown:id) - β Fixed delete synchronization between instances - implemented differential sync to detect and apply deletions when entities are missing from server responses, including handling empty entity lists
- β Fixed presence reactions not appearing in peer instances - implemented proper refresh-presence message handling to convert reaction data to visible UI reactions
- β Fixed cursors, typing indicators, and avatars not working in peer instances - implemented complete presence data detection and routing in refresh-presence messages to handle all presence types
- β Fixed avatars page showing only 1 user instead of both users - preserved local user's presence when processing refresh-presence messages to match React SDK behavior
- β Fixed avatar presence data extraction and room ID consistency - corrected nested data structure extraction from refresh-presence messages and unified room key format usage
- β Fixed typing indicators showing 'Someone' instead of actual user names - updated typing page to set initial presence with userName and display actual user names in typing indicators
- β
Added comprehensive hierarchical logging system - using
loggingpackage for better debugging and monitoring of sync operations - β Enhanced sync engine with proper attribute UUID mapping - transactions now use correct InstantDB attribute UUIDs instead of attribute names
π Documentation #
- β Updated README with all new APIs and examples
- β
Created
ADVANCED_FEATURES.mdcomprehensive feature guide - β
Added
MIGRATION_GUIDE.mdfor upgrading existing code - β Updated example applications showcasing new room-based presence APIs
π± Example Applications Updated #
- β Cursors demo updated to use room-based presence API
- β Reactions demo updated with room-scoped reactions
- β Typing indicators demo updated with room-scoped typing
- β Avatars demo updated with room-scoped presence
- β
Todos demo updated to showcase new
txnamespace API
π§ Breaking Changes #
None! This release is fully backward compatible. All existing APIs continue to work.
π― Migration Path #
- Immediate: New projects can use new APIs from day one
- Gradual: Existing projects can migrate incrementally at their own pace
- Optional: Migration provides better performance and developer experience but is not required
0.1.2 #
π Documentation & Web Support #
- Added web platform setup documentation with SQLite web worker configuration
- Added documentation link to pub.flutter-io.cn pointing to https://instantdb-flutter-docs.pages.dev
- Improved setup instructions to prevent web worker initialization errors
0.1.1 #
π§ Fixes #
- Fixed incorrect GitHub repository links in pubspec.yaml and CONTRIBUTING.md
- Repository links now correctly point to https://github.com/pillowsoft/instantdb_flutter
0.1.0 #
π Initial Release #
Core Features
- β Real-time synchronization with InstantDB backend
- β Offline-first local storage with SQLite triple store
- β Reactive UI updates using Signals
- β InstaQL query language support
- β Transaction system with optimistic updates
- β Authentication system integration
- β Schema validation and type safety
Flutter Integration
- β
InstantProviderfor dependency injection - β
InstantBuilderandInstantBuilderTypedreactive widgets - β
AuthBuilderfor authentication state management - β
Watchwidget for reactive UI updates - β
ConnectionStatusBuilderfor network status
Presence System
- β Real-time cursor tracking
- β Typing indicators
- β Emoji reactions
- β User presence status
- β Room-based collaboration features
Developer Experience
- β Comprehensive example application
- β Full test coverage
- β TypeScript-style API design
- β Hot reload support
- β Debug tooling integration
0.0.1 #
- Initial development release with basic InstantDB integration