> ## Documentation Index
> Fetch the complete documentation index at: https://docs.powersync.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Dart/Flutter SDK

> Use PowerSync in Dart and Flutter apps.

<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

Get started quickly by using the self-hosted **Flutter** + **Supabase** template

📂 GitHub Repo
[https://github.com/powersync-community/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 can handle schema changes gracefully without requiring 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**: To sync data between your client-side app and your backend source database, you must have completed the necessary setup for PowerSync, which includes connecting your source database to the PowerSync Service and deploying Sync Streams (or legacy Sync Rules) (steps 1-4 in the [Setup Guide](/intro/setup-guide)).

<Note>
  For this reference document, we assume that you have created a Flutter project and have 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 first step is to define the client-side schema, which refers to the schema for the managed SQLite database exposed by the PowerSync Client SDKs, that your app can read from and write to. The client-side schema is typically mainly derived from your backend source database schema and your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)), but can also include other tables such as local-only tables. Note that schema migrations are not required on the SQLite database due to the schemaless nature of the [PowerSync protocol](/architecture/powersync-protocol): schemaless data is synced to the client-side SQLite database, and the client-side schema is then applied to that data using *SQLite views* to allow for structured querying of the data. The schema is applied when the local PowerSync database is constructed (as we'll show in the next step).

<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 will be generated based off your Sync Streams/Rules.

  Similar functionality exists in the [CLI](/tools/cli).

  **Note:** The generated schema will not include an `id` column, as the client SDK automatically creates an `id` column of type `text`. Consequently, it is not necessary to specify an `id` column in your schema. For additional information on IDs, refer to [Client ID](/sync/advanced/client-id).
</Tip>

The types available are `text`, `integer` and `real`. These should map directly to the values produced by your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)). If a value doesn't match, it is cast automatically. For details on how backend source database types are mapped to the 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>
  **Note**: No need to declare a primary key `id` column, as PowerSync will automatically create this.
</Note>

### 2. Instantiate the PowerSync Database

Next, you need to instantiate the PowerSync database. PowerSync streams changes from your backend source database into the client-side SQLite database, based on your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)). In your client-side app, you can read from and write to the local SQLite database, whether the user is online or offline.

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**:

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

Once you've instantiated your 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 will be created in the next step.

<Tip>
  **Note**: This section assumes you want to use PowerSync to sync your backend source database with SQLite in your app. If you only want to use PowerSync to manage your local SQLite database without sync, instantiate the PowerSync database without calling `connect()` and refer to our [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 PowerSync backend connector provides the connection between your application backend and the PowerSync client-side managed SQLite database. It is used to:

1. Retrieve an auth token to connect to the PowerSync instance.
2. Upload client-side writes to your backend API. Any writes that are made to the SQLite database are placed into an upload queue by the PowerSync Client SDK and automatically uploaded to your app backend (where you apply those changes to the backend source database) when the user is connected.

Accordingly, the connector must implement two methods:

1. [PowerSyncBackendConnector.fetchCredentials](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncBackendConnector/fetchCredentials.html) - This method is automatically invoked by the PowerSync Client SDK to obtain authentication credentials. The SDK caches credentials internally and only calls this method when needed (e.g. on initial 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 instructions on how the credentials should be generated.
2. [PowerSyncBackendConnector.uploadData](https://pub.dev/documentation/powersync/latest/powersync/PowerSyncBackendConnector/uploadData.html) - This method will be automatically invoked by the PowerSync Client SDK whenever it needs to upload client-side writes to your app's backend API. You need to implement how those writes are processed and uploaded in this method. See [When `uploadData()` is Called](/configuration/app-backend/client-side-integration#when-uploaddata-is-called) for details on triggers, throttling, and retry behavior, and [Writing Client Changes](/handling-writes/writing-client-changes) for considerations on 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/reference/flutter#3-integrate-with-your-backend
  @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();
  }
}

```

## 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:

* [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 source tables are modified.
* [PowerSyncDatabase.execute](/client-sdks/reference/flutter#mutations-powersync.execute) - execute a write (INSERT/UPDATE/DELETE) query.

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

```dart lib/models/todolist.dart theme={null}
/// 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](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteQueries/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/SqliteQueries/getOptional.html) 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:

```dart lib/widgets/lists_widget.dart theme={null}
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](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteQueries/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 '../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](https://pub.dev/documentation/powersync/latest/sqlite_async/SqliteQueries/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/powersync/PowerSyncDatabase/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 '../main.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

Since version 1.1.2 of the SDK, logging is enabled by default and outputs logs from PowerSync to the console in debug mode.

## 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-sdk).

## Upgrading the SDK

To upgrade to a newer version of the PowerSync package, run the below command in your project folder:

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