Installation

Requirements

Add Dependency

Add PocketSync to your pubspec.yaml file:

dependencies:
  pocketsync_flutter: ^0.0.11

Or install via command line:

flutter pub add pocketsync_flutter

Basic Setup

  1. Create a project in the PocketSync console
  2. Initialize PocketSync in your app:
import 'package:pocketsync_flutter/pocketsync_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  final dbPath = join(await getDatabasesPath(), 'my_app.db');
  
  try {
    await PocketSync.initialize(
      dbPath: dbPath,
      options: PocketSyncOptions(
        projectId: 'your-project-id',
        authToken: 'your-auth-token',
        serverUrl: 'https://api.pocketsync.dev',
      ),
      databaseOptions: databaseOptions,
    );

    await PocketSync.instance.setUserId(userId: 'user-123');
    await PocketSync.instance.start();
  } catch (e) {
    print('Failed to initialize PocketSync: $e');
  }
}

Configuration

Database Schema

When designing your database schema, follow these best practices:

// In your database initialization
await db.execute('''
  CREATE TABLE todos (
    id TEXT PRIMARY KEY NOT NULL, // Use UUID instead of auto-increment
    title TEXT NOT NULL,
    is_completed INTEGER NOT NULL DEFAULT 0,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
  )
''');

Key points:

  • Use UUIDs for primary keys
  • Include timestamp fields for sync optimization
  • Use appropriate data types for each column

Basic Operations

// Get database instance
final db = PocketSync.instance.database;

// Insert data
await db.insert('todos', {
  'id': const Uuid().v4(),
  'title': 'Buy groceries',
  'is_completed': 0,
  'created_at': DateTime.now().millisecondsSinceEpoch,
  'updated_at': DateTime.now().millisecondsSinceEpoch,
});

// Query data
final todos = await db.query('todos',
  where: 'is_completed = ?',
  whereArgs: [0],
);

// Update data
await db.update('todos',
  {'is_completed': 1},
  where: 'id = ?',
  whereArgs: ['todo-123'],
);

// Delete data
await db.delete('todos',
  where: 'id = ?',
  whereArgs: ['todo-123'],
);

Watch for Changes

PocketSync provides a powerful watch API to monitor database changes:

// Watch all todos
final todosStream = db.watch('SELECT * FROM todos');

// Use in StreamBuilder
StreamBuilder<List<Map<String, dynamic>>>(
  stream: todosStream,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data!.length,
        itemBuilder: (context, index) => TodoItem(todo: snapshot.data![index]),
      );
    }
    return const CircularProgressIndicator();
  },
);

Next Steps