flutter_sync_client 0.1.9
flutter_sync_client: ^0.1.9 copied to clipboard
Real-time data synchronization plugin for Flutter with Hive and Socket.IO
Flutter Sync Client #
Real-time data synchronization plugin for Flutter with Hive and Socket.IO. Supports both untyped and type-safe collections with fast O(1) indexed searching.
Features #
- ✅ Real-time synchronization with Socket.IO
- ✅ Offline support with Hive local storage
- ✅ Type-safe collections with generics (v0.1.1+)
- ✅ Fast O(1) searching with in-memory indexing
- ✅ Automatic reconnection and conflict resolution
- ✅ Real-time streams for reactive UI updates
- ✅ Authentication support with JWT tokens
- ✅ Energy efficient with smart caching
- ✅ Flutter Web support - works in browsers (v0.1.4+)
- ✅ Production server support - configurable transports and paths
Installation #
Add to your pubspec.yaml:
dependencies:
flutter_sync_client: ^0.1.5
Then run:
flutter pub get
Usage #
1. Initialize Client #
final syncClient = SyncClient(
serverUrl: 'http://your-server.com:3000',
);
await syncClient.initialize();
2. Get Collection Reference #
final todosCollection = syncClient.collection('todos');
3. Listen to Changes #
StreamBuilder<List<Map<String, dynamic>>>(
stream: todosCollection.stream,
builder: (context, snapshot) {
final todos = snapshot.data ?? [];
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(title: Text(todos[index]['title']));
},
);
},
)
4. CRUD Operations #
// Add
await todosCollection.add({
'title': 'Buy milk',
'completed': false,
});
// Update
await todosCollection.update(id, {
'completed': true,
});
// Delete
await todosCollection.delete(id);
// Get single item
final todo = await todosCollection.get(id);
// Get all items
final todos = await todosCollection.getAll();
5. Connection Status #
StreamBuilder<bool>(
stream: syncClient.connectionStream,
builder: (context, snapshot) {
final isConnected = snapshot.data ?? false;
return Icon(
isConnected ? Icons.cloud_done : Icons.cloud_off,
);
},
)
Type-Safe Collections (v0.1.1+) #
Work with your own model classes and enjoy O(1) fast searches with indexed fields!
1. Define Your Model #
class Todo {
final String id;
final String title;
final bool completed;
Todo({required this.id, required this.title, required this.completed});
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
id: json['id'].toString(),
title: json['title'] as String,
completed: json['completed'] as bool,
);
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'completed': completed,
};
}
2. Create Typed Collection #
final todos = syncClient.typedCollection<Todo>(
'todos',
fromJson: Todo.fromJson,
toJson: (todo) => todo.toJson(),
getId: (todo) => todo.id,
indexedFields: ['completed'], // Fast O(1) search by completion status!
);
3. Use Type-Safe API #
// Insert with type safety
await todos.insert(Todo(id: '1', title: 'Buy milk', completed: false));
// Fast O(1) indexed search
final completed = await todos.findByField('completed', true);
// Custom queries
final pending = await todos.where((todo) => !todo.completed);
// Get by ID (O(1) from cache)
final todo = await todos.get('1');
// Real-time typed stream
todos.stream.listen((List<Todo> todoList) {
print('Todos updated: ${todoList.length}');
});
Performance Benefits #
| Operation | Untyped | Typed + Indexed |
|---|---|---|
| Search by field | O(n) | O(1) |
| Get by ID | O(log n) | O(1) |
| Type safety | ❌ Runtime | ✅ Compile-time |
See TYPED_COLLECTIONS.md for comprehensive documentation.
Authentication #
Support for JWT token authentication:
final client = SyncClient(
serverUrl: 'http://your-server.com:3000',
authToken: 'your-jwt-token',
);
// Or set token later
client.setAuthToken('new-token');
// Or use token provider for automatic refresh
client.setTokenProvider(() async {
return await getTokenFromStorage();
});
Advanced Features #
Upsert Operations #
Insert or update in a single operation:
// Works with both typed and untyped collections
await todos.upsert(Todo(id: '1', title: 'Updated', completed: true));
Query Methods (Typed Collections) #
// Count items
final total = await todos.count();
final completedCount = await todos.count((todo) => todo.completed);
// Find first match
final firstPending = await todos.findFirst((todo) => !todo.completed);
// Get all items
final allTodos = await todos.getAll();
Offline-First Architecture #
All changes are:
- Saved locally to Hive immediately
- Queued for sync when offline
- Automatically synced when connection is restored
- Merged with server changes intelligently
Server Setup #
This client requires a Socket.IO server. Basic server example:
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
socket.on('subscribe', (collection) => {
socket.join(collection);
// Send initial data
socket.emit('initial_data', {
collection,
data: [],
serverTime: Date.now()
});
});
socket.on('insert', ({ collection, items }) => {
// Save to database
// Broadcast to other clients
socket.to(collection).emit('data_inserted', { collection, items });
});
});
See the server examples for complete implementations.
Platform Support #
| Platform | Status | Notes |
|---|---|---|
| Android | ✅ Full Support | Native Hive + Socket.IO |
| iOS | ✅ Full Support | Native Hive + Socket.IO |
| Web | ✅ Full Support | IndexedDB + Socket.IO |
| Windows | ⚠️ Partial | Hive limitations |
| macOS | ⚠️ Partial | Hive limitations |
| Linux | ⚠️ Partial | Hive limitations |
See WEB_SUPPORT.md for web-specific details and CORS configuration.
Production Server Configuration (v0.1.4+) #
Configure for production servers with custom Socket.IO settings:
final client = SyncClient(
serverUrl: 'https://your-production-server.com',
socketPath: '/socket.io/', // Custom Socket.IO path
transports: ['polling'], // Use polling for better compatibility
reconnectionAttempts: 5,
reconnectionDelay: 1000,
timeout: 10000,
);
Documentation #
- Type-Safe Collections Guide - Comprehensive guide for typed collections with indexing
- Web Support Guide - Flutter Web setup and CORS configuration
- API Reference - Complete API documentation
- Architecture Overview - Internal architecture and development guide
Example Apps #
- Basic Todo App - Simple todo list with offline support (cross-platform)
- Web Example - Flutter Web demo with real-time sync
- Authenticated App - Todo app with JWT authentication
- Typed Collections Example - Demonstrates type-safe collections
Run Examples #
# Run on mobile/desktop
flutter run
# Run on web
flutter run -d chrome -t lib/web_example.dart
# Build for web
flutter build web --release
Testing Offline Sync #
cd example
flutter run
Test Scenarios:
- Add todos while online
- Toggle completion
- Delete todos
- Close app and reopen (data persists)
- Stop server and make changes (offline mode)
- Restart server (auto sync)
- Open on multiple devices simultaneously (real-time sync)
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
Issues #
Found a bug or have a feature request? Please open an issue on GitHub.
License #
MIT License - see LICENSE file for details.
Author #
M Sampath Kumara - GitHub