SDK Features

  • Real-time streaming of database changes: Changes made by one user are instantly streamed to all other users with access to that data. This keeps clients automatically in sync without manual polling or refresh logic.
  • Direct access to a local SQLite database: Data is stored locally, so apps can read and write instantly without network calls. This enables offline support and faster user interactions.
  • Asynchronous background execution: The SDK performs database operations in the background to avoid blocking the application’s main thread. This means that apps stay responsive, even during heavy data activity.
  • Query subscriptions for live updates: The SDK supports query subscriptions that automatically push real-time updates to client applications as data changes, keeping your UI reactive and up to date.
  • Automatic schema management: PowerSync syncs schemaless data and applies a client-defined schema using SQLite views. This architecture means that PowerSync SDKs can handle schema changes gracefully without requiring explicit migrations on the client-side.

Web support is currently in a beta release. Refer to Flutter Web Support for more details.

Installation

Add the PowerSync pub.dev package to your project:

flutter pub add powersync

Getting Started

Before implementing the PowerSync SDK in your project, make sure you have completed these steps:

For this reference document, we assume that you have created a Flutter project and have the following directory structure:

lib/
├── models/
    ├── schema.dart
    └── todolist.dart
├── powersync/
    ├── my_backend_connector.dart
    └── powersync.dart
├── widgets/
    ├── lists_widget.dart
    ├── todos_widget.dart
├── main.dart

1. Define the Schema

The first step is defining the schema for the local SQLite database. This will be provided as a schema parameter to the PowerSyncDatabase constructor.

This schema represents a “view” of the downloaded data. No migrations are required — the schema is applied directly when the PowerSync database is constructed.

Generate schema automatically

In the dashboard, the schema can be generated based off your sync rules by right-clicking on an instance and selecting Generate client-side schema.

Similar functionality exists in the CLI.

The types available are text, integer and real. These should map directly to the values produced by the Sync Rules. If a value doesn’t match, it is cast automatically. For details on how Postgres types are mapped to the types below, see the section on Types in the Sync Rules documentation.

Example:

lib/models/schema.dart
import 'package:powersync/powersync.dart';

const schema = Schema(([
  Table('todos', [
    Column.text('list_id'),
    Column.text('created_at'),
    Column.text('completed_at'),
    Column.text('description'),
    Column.integer('completed'),
    Column.text('created_by'),
    Column.text('completed_by'),
  ], indexes: [
    // Index to allow efficient lookup within a list
    Index('list', [IndexedColumn('list_id')])
  ]),
  Table('lists', [
    Column.text('created_at'),
    Column.text('name'),
    Column.text('owner_id')
  ])
]));

Note: No need to declare a primary key id column, as PowerSync will automatically create this.

2. Instantiate the PowerSync Database

Next, you need to instantiate the PowerSync database — this is the core managed client-side database.

Its primary functions are to record all changes in the local database, whether online or offline. In addition, it automatically uploads changes to your app backend when connected.

To instantiate PowerSyncDatabase, inject the Schema you defined in the previous step and a file path — it’s important to only instantiate one instance of PowerSyncDatabase per file.

Example:

lib/powersync/powersync.dart
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import '../main.dart';
import '../models/schema.dart';

openDatabase() async {
  final dir = await getApplicationSupportDirectory();
  final path = join(dir.path, 'powersync-dart.db');

  // Set up the database
  // Inject the Schema you defined in the previous step and a file path
  db = PowerSyncDatabase(schema: schema, path: path);
  await db.initialize();
}

Once you’ve instantiated your PowerSync database, you will need to call the connect() method to activate it. This method requires the backend connector that will be created in the next step.

lib/main.dart
import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart';

import 'powersync/powersync.dart';

late PowerSyncDatabase db;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await openDatabase();
  runApp(const DemoApp());
}

class DemoApp extends StatefulWidget {
  const DemoApp({super.key});

  
  State<DemoApp> createState() => _DemoAppState();
}

class _DemoAppState extends State<DemoApp> {
  
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Demo',
        home: // TODO: Implement your own UI here.
        // You could listen for authentication state changes to connect or disconnect from PowerSync
        StreamBuilder(
            stream: // TODO: some stream,
            builder: (ctx, snapshot) {,
              // TODO: implement your own condition here
              if ( ... ) {
                // Uses the backend connector that will be created in the next step
                db.connect(connector: MyBackendConnector());
                // TODO: implement your own UI here
              }
            },
        )
    );
  }
}

3. Integrate with your Backend

The PowerSync backend connector provides the connection between your application backend and the PowerSync client-slide managed SQLite database.

It is used to:

  1. Retrieve an auth token to connect to the PowerSync instance.
  2. Apply local changes on your backend application server (and from there, to Postgres)

Accordingly, the connector must implement two methods:

  1. PowerSyncBackendConnector.fetchCredentials - This is called every couple of minutes and is used to obtain credentials for your app backend API. -> See Authentication Setup for instructions on how the credentials should be generated.
  2. PowerSyncBackendConnector.uploadData - Use this to upload client-side changes to your app backend. -> See Writing Client Changes for considerations on the app backend implementation.

Example:

lib/powersync/my_backend_connector.dart
import 'package:powersync/powersync.dart';

class MyBackendConnector extends PowerSyncBackendConnector {
  PowerSyncDatabase db;

  MyBackendConnector(this.db);
  
  Future<PowerSyncCredentials?> fetchCredentials() async {
    // Implement fetchCredentials to obtain a JWT from your authentication service
    // If you're using Supabase or Firebase, you can re-use the JWT from those clients, see
    // - https://docs.powersync.com/installation/authentication-setup/supabase-auth
    // - https://docs.powersync.com/installation/authentication-setup/firebase-auth

    // See example implementation here: https://pub.dev/documentation/powersync/latest/powersync/DevConnector/fetchCredentials.html

    return PowerSyncCredentials(
      endpoint: 'https://xxxxxx.powersync.journeyapps.com',
      // Use a development token (see Authentication Setup https://docs.powersync.com/installation/authentication-setup/development-tokens) to get up and running quickly
      token: 'An authentication token'
    );
  }

  // Implement uploadData to send local changes to your backend service
  // You can omit this method if you only want to sync data from the server to the client
  // See example implementation here: https://docs.powersync.com/client-sdk-references/flutter#3-integrate-with-your-backend
  
  Future<void> uploadData(PowerSyncDatabase database) async {
    // This function is called whenever there is data to upload, whether the
    // device is online or offline.
    // If this call throws an error, it is retried periodically.

    final transaction = await database.getNextCrudTransaction();
    if (transaction == null) {
      return;
    }

    // The data that needs to be changed in the remote db
    for (var op in transaction.crud) {
      switch (op.op) {
        case UpdateType.put:
          // TODO: Instruct your backend API to CREATE a record
        case UpdateType.patch:
          // TODO: Instruct your backend API to PATCH a record
        case UpdateType.delete:
        //TODO: Instruct your backend API to DELETE a record
      }
    }

    // Completes the transaction and moves onto the next one
    await transaction.complete();
  }
}

Using PowerSync: CRUD functions

Once the PowerSync instance is configured you can start using the SQLite DB functions.

The most commonly used CRUD functions to interact with your SQLite data are:

For the following examples, we will define a TodoList model class that represents a List of todos.

lib/models/todolist.dart
/// This is a simple model class representing a TodoList
class TodoList {
  final int id;
  final String name;
  final DateTime createdAt;
  final DateTime updatedAt;

  TodoList({
    required this.id,
    required this.name,
    required this.createdAt,
    required this.updatedAt,
  });

  factory TodoList.fromRow(Map<String, dynamic> row) {
    return TodoList(
      id: row['id'],
      name: row['name'],
      createdAt: DateTime.parse(row['created_at']),
      updatedAt: DateTime.parse(row['updated_at']),
    );
  }
}

Fetching a Single Item

The get method executes a read-only (SELECT) query and returns a single result. It throws an exception if no result is found. Use getOptional to return a single optional result (returns null if no result is found).

The following is an example of selecting a list item by ID

lib/widgets/lists_widget.dart
import '../main.dart';
import '../models/todolist.dart';

Future<TodoList> find(id) async {
  final result = await db.get('SELECT * FROM lists WHERE id = ?', [id]);
  return TodoList.fromRow(result);
}

Querying Items (PowerSync.getAll)

The getAll method returns a set of rows from a table.

lib/widgets/lists_widget.dart
import 'package:powersync/sqlite3.dart';
import '../main.dart';

Future<List<String>> getLists() async {
  ResultSet results = await db.getAll('SELECT id FROM lists WHERE id IS NOT NULL');
  List<String> ids = results.map((row) => row['id'] as String).toList();
  return ids;
}

Watching Queries (PowerSync.watch)

The watch method executes a read query whenever a change to a dependent table is made.

lib/widgets/todos_widget.dart
import 'package:flutter/material.dart';
import '../main.dart';
import '../models/todolist.dart';

// Example Todos widget
class TodosWidget extends StatelessWidget {
  const TodosWidget({super.key});

  
  Widget build(BuildContext context) {
    return StreamBuilder(
      // You can watch any SQL query
      stream: db
          .watch('SELECT * FROM lists ORDER BY created_at, id')
          .map((results) {
        return results.map(TodoList.fromRow).toList(growable: false);
      }),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          // TODO: implement your own UI here based on the result set
          return ...;
        } else {
        return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }
}

Mutations (PowerSync.execute)

The execute method can be used for executing single SQLite write statements.

lib/widgets/todos_widget.dart
import 'package:flutter/material.dart';
import '../main.dart';

// Example Todos widget
class TodosWidget extends StatelessWidget {
  const TodosWidget({super.key});

  
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () async {
        await db.execute(
          'INSERT INTO lists(id, created_at, name, owner_id) VALUES(uuid(), datetime(), ?, ?)',
          ['name', '123'],
        );
      },
      tooltip: '+',
      child: const Icon(Icons.add),
    );
  }
}

Additional Usage Examples

See Usage Examples for further examples of the SDK.

ORM Support

See Flutter ORM Support for details.

Troubleshooting

See Troubleshooting for pointers to debug common issues.