> ## Documentation Index
> Fetch the complete documentation index at: https://powersync-sync-streams-nav.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Dart/Flutter SDK

> Use PowerSync in Dart and Flutter apps.

```text Build with AI icon="sparkles" wrap theme={null}
Install the PowerSync Agent Skills with: npx skills add powersync-ja/agent-skills. Then follow the skills to onboard this project to PowerSync using the Dart/Flutter SDK.
```

<CardGroup cols={3}>
  <Card title="PowerSync SDK on pub.dev" icon="cube" href="https://pub.dev/packages/powersync">
    The SDK is distributed via pub.dev
  </Card>

  <Card title="Source Code" icon="github" href="https://github.com/powersync-ja/powersync.dart">
    Refer to the `powersync.dart` repo on GitHub
  </Card>

  <Card title="API Reference" icon="book" href="https://pub.dev/documentation/powersync/latest/powersync/powersync-library.html">
    Full API reference for the SDK
  </Card>

  <Card title="Example Projects" icon="code" href="/intro/examples">
    Gallery of example projects/demo apps built with Flutter and PowerSync
  </Card>

  <Card title="Changelog" icon="megaphone" href="https://releases.powersync.com/announcements/flutter-client-sdk">
    Changelog for the SDK
  </Card>
</CardGroup>

## Quickstart

To start from a template, use the self-hosted Flutter and Supabase template: [flutter-powersync-supabase](https://github.com/powersync-community/flutter-powersync-supabase).

## 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 handle schema changes without explicit migrations on the client side.

<Note>
  Web support is currently in a beta release. Refer to [Flutter Web Support](/client-sdks/frameworks/flutter-web-support) for more details.
</Note>

## Installation

Add the [PowerSync pub.dev package](https://pub.dev/packages/powersync) to your project:

```bash theme={null}
dart pub add powersync
```

## Getting Started

**Prerequisites:** Before you start, connect your source database to the PowerSync Service and deploy Sync Streams. These are steps 1-4 in the [Setup Guide](/intro/setup-guide).

<Note>
  This reference assumes a Flutter project with the following directory structure:

  ```plaintext theme={null}
  lib/
  ├── models/
      ├── schema.dart
      └── todolist.dart
  ├── powersync/
      ├── my_backend_connector.dart
      └── powersync.dart
  ├── widgets/
      ├── lists_widget.dart
      ├── todos_widget.dart
  ├── main.dart
  ```
</Note>

### 1. Define the Client-Side Schema

The client-side schema defines the tables and columns of the SQLite database that the PowerSync client SDK manages and that your app reads from and writes to. It is usually derived from your backend database schema and your [Sync Streams](/sync/streams/overview), and it can also include [local-only tables](/client-sdks/advanced/local-only-usage). You apply the schema when you instantiate the database in the next step.

Schema migrations are not required. The SDK syncs schemaless data and applies the schema to that data with SQLite views. The exception is [raw tables](/client-sdks/advanced/raw-tables), which you create and migrate yourself.

<Tip>
  **Generate schema automatically**

  In the [PowerSync Dashboard](https://dashboard.powersync.com/), select your project and instance and click the **Connect** button in the top bar to generate the client-side schema in your preferred language. The schema is generated from your Sync Streams. The [CLI](/tools/cli) offers the same function.

  The generated schema does not include an `id` column. The client SDK creates an `id` column of type `text` automatically, so you do not need to declare it. See [Client ID](/sync/advanced/client-id) for details.
</Tip>

The available column types are `text`, `integer`, and `real`. These should match the values produced by your Sync Streams. If a value does not match, it is cast automatically. For details on how source database types map to SQLite types, see [Types](/sync/types).

**Example:**

```dart lib/models/schema.dart theme={null}
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>
  You do not need to declare an `id` column. PowerSync creates it automatically.
</Note>

### 2. Instantiate the PowerSync Database

Next, instantiate the PowerSync database. PowerSync streams changes from your backend source database into the client-side SQLite database, based on your Sync Streams. Your app reads from and writes to this local database whether the user is online or offline.

To instantiate `PowerSyncDatabase`, pass the schema you defined in the previous step and a file path. Create only one `PowerSyncDatabase` instance per file.

**Example:**

```dart lib/powersync/powersync.dart theme={null}
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import '../models/schema.dart';

// TODO: Use riverpod, providers or another state management
// approach instead of a global variable to store the database.
late PowerSyncDatabase db;

Future<void> 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();
}
```

After you instantiate the PowerSync database, call the [connect()](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncDatabase/connect.html) method to sync data with your backend. This method requires the backend connector that you create in the next step.

<Tip>
  This section assumes that you use PowerSync to sync your backend source database with SQLite in your app. To manage a local SQLite database without sync, instantiate the PowerSync database without calling `connect()` and see the [Local-Only](/client-sdks/advanced/local-only-usage) guide.
</Tip>

```dart lib/main.dart {26} theme={null}
import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart';

import 'powersync/powersync.dart';

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

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

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

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

class _DemoAppState extends State<DemoApp> {
  @override
  void initState() {
    super.initState();

    // TODO: Observe a condition to connect / disconnect.
    db.connect(connector: MyBackendConnector());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      // TODO: Implement your own UI here.
    );
  }
}
```

### 3. Integrate with Your Backend

The backend connector connects the PowerSync client SDK to your application backend. The SDK uses it to:

1. Get an auth token to connect to the PowerSync instance.
2. Upload client-side writes to your backend API. The SDK places every write to the SQLite database in an upload queue and uploads the queue to your backend when the user is connected. Your backend then applies the changes to the source database.

The connector must implement two methods:

1. [PowerSyncBackendConnector.fetchCredentials](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncBackendConnector/fetchCredentials.html) - The SDK calls this method to get authentication credentials. It caches the credentials and calls the method again only when needed, for example on the first connection or when the token is near expiry. See [When `fetchCredentials()` is Called](/configuration/app-backend/client-side-integration#when-fetchcredentials-is-called) for details and [Authentication Setup](/configuration/auth/overview) for how to generate credentials.
2. [PowerSyncBackendConnector.uploadData](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncBackendConnector/uploadData.html) - The SDK calls this method whenever it has client-side writes to upload to your backend API. Implement how those writes are processed and uploaded. See [When `uploadData()` is Called](/configuration/app-backend/client-side-integration#when-uploaddata-is-called) for triggers, throttling, and retry behavior, and [Writing Client Changes](/handling-writes/writing-client-changes) for the app backend implementation.

**Example:**

```dart lib/powersync/my_backend_connector.dart theme={null}
import 'package:powersync/powersync.dart';

class MyBackendConnector extends PowerSyncBackendConnector {
  PowerSyncDatabase db;

  MyBackendConnector(this.db);
  @override
  Future<PowerSyncCredentials?> fetchCredentials() async {
    // Implement fetchCredentials to obtain a JWT from your authentication service. 
    // See https://docs.powersync.com/configuration/auth/overview
    // 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/configuration/auth/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-sdks/usage-examples#send-changes-in-local-data-to-your-backend-service
  @override
  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();
  }
}

```

### 4. Subscribe to Sync Streams

Streams defined with `auto_subscribe: true` start syncing as soon as the client connects. For all other streams, your app must subscribe before their data downloads. The basic pattern is: subscribe to a stream, wait for its data to sync, then unsubscribe when the data is no longer needed.

```dart theme={null}
// Subscribe to a stream with parameters
final sub = await db.syncStream('list_todos', {'list_id': 'abc123'}).subscribe();

// Wait for the initial data to sync
await sub.waitForFirstSync();

// The stream's rows are now in the local SQLite database.
// TODO: Read the todos for this list with a local query.

// When the data is no longer needed
sub.unsubscribe();
```

After you unsubscribe, the synced data stays in the local database for the stream's time-to-live (TTL), which is 24 hours by default. If the app subscribes again within that time, the data is already available. See [Client-Side Usage](/sync/streams/client-usage) for framework hooks, per-subscription sync status, custom TTLs, priority overrides, and connection parameters.

## Using PowerSync: CRUD Functions

Once the PowerSync database is connected and your streams have synced, the data is in the local SQLite database.

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

* [PowerSyncDatabase.get](/client-sdks/reference/flutter#fetching-a-single-item) - get (`SELECT`) a single row from a table.
* [PowerSyncDatabase.getAll](/client-sdks/reference/flutter#querying-items-powersync-getall) - get (`SELECT`) a set of rows from a table.
* [PowerSyncDatabase.watch](/client-sdks/reference/flutter#watching-queries-powersync-watch) - execute a read query every time a dependent table changes.
* [PowerSyncDatabase.execute](/client-sdks/reference/flutter#mutations-powersync-execute) - execute a write (`INSERT`/`UPDATE`/`DELETE`) query.

The following examples use this `TodoList` model class:

```dart lib/models/todolist.dart theme={null}
/// A model class representing a row in the lists table
class TodoList {
  final String id;
  final String name;
  final DateTime createdAt;
  final String ownerId;

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

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

### Fetching a Single Item

The [get](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteConnection/get.html) method executes a read-only (SELECT) query and returns a single result. It throws an exception if no result is found. Use [getOptional](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteConnection/getOptional.html) to return a single optional result (returns `null` if no result is found).

The following example selects a list by ID:

```dart lib/widgets/lists_widget.dart theme={null}
import '../powersync/powersync.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](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteConnection/getAll.html) method returns a set of rows from a table.

```dart lib/widgets/lists_widget.dart theme={null}
import 'package:powersync/sqlite3.dart';
import '../powersync/powersync.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](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncDatabase/watch.html) method executes a read query whenever a change to a dependent table is made.

```dart theme={null}
StreamBuilder(
  stream: db.watch('SELECT * FROM lists WHERE state = ?', ['pending']),
  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](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteConnection/execute.html) method can be used for executing single SQLite write statements.

```dart lib/widgets/todos_widget.dart {12-15} theme={null}
import 'package:flutter/material.dart';
import '../powersync/powersync.dart';

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

  @override
  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),
    );
  }
}
```

## Configure Logging

Logging is enabled by default and outputs logs from PowerSync to the console in debug mode.

To disable this, or to configure logging in release-mode configurations, use the `logger` parameter on the `PowerSyncDatabase` constructor.
PowerSync uses [`package:logging`](https://pub.dev/packages/logging) to emit logs. See that package for additional information.

## Custom HTTP Clients and Headers

PowerSync uses a streaming HTTP response to connect to the PowerSync Service. The SDK uses the default `Client()` from the
[http package](https://pub.dev/packages/http) for that, which relies on `HttpClient` from `dart:io` on native platforms and `fetch()`
on the web.

You can also supply a custom HTTP client. This can be used to enable a faster HTTP implementation like [`cronet_http`](https://pub.dev/packages/cronet_http),
or to add custom request headers that may be required if you run the PowerSync Service behind a reverse-proxy.

```dart theme={null}
import 'package:http/http.dart';
import 'package:powersync/powersync.dart';

final class _AddHeaderClient extends BaseClient {
  final Client inner;

  _AddHeaderClient([Client? inner]) : inner = inner ?? Client();

  @override
  Future<StreamedResponse> send(BaseRequest request) {
    request.headers['x-my-custom-header'] = 'set for all requests';
    return inner.send(request);
  }

  @override
  void close() => inner.close();
}

Future<void> connect(PowerSyncDatabase db) async {
  await db.connect(
    connector: MyBackendConnector(db),
    options: SyncOptions(
      httpClient: _AddHeaderClient.new
    ),
  );
}
```

<Note>
  On the web, PowerSync uses a shared worker for the sync process. As Dart objects cannot be shared between tabs and workers, the worker uses a
  random tab as a proxy to send requests. This can slow down the sync process slightly.
</Note>

## Additional Usage Examples

For more usage examples including accessing connection status, monitoring sync progress, and waiting for initial sync, see the [Usage Examples](/client-sdks/usage-examples) page.

## ORM Support

See [ORM Support](/client-sdks/orms/flutter-orm-support) for details.

## Troubleshooting

Use the [Dart & Flutter DevTools extension](/tools/dart-devtools-extension) to inspect live databases, run SQL queries, and view sync status without leaving your IDE. Available from `powersync` v2.1.0 in debug builds.

See [Troubleshooting](/debugging/troubleshooting) for pointers to debug common issues.

## Supported Platforms

See [Supported Platforms -> Dart SDK](/resources/supported-platforms#dart/flutter).

## Upgrading the SDK

To upgrade the PowerSync package, run the following command in your project folder:

```bash theme={null}
dart pub upgrade powersync
```
