Skip to content

Latest commit

Β 

History

History
380 lines (290 loc) Β· 15.3 KB

File metadata and controls

380 lines (290 loc) Β· 15.3 KB
title Dart/Flutter SDK
description Full SDK guide for using PowerSync in Dart/Flutter clients
sidebarTitle SDK Reference

import SdkFeatures from '/snippets/sdk-features.mdx'; import FlutterInstallation from '/snippets/flutter/installation.mdx'; import FlutterWatch from '/snippets/flutter/basic-watch-query.mdx'; import GenerateSchemaAutomatically from '/snippets/generate-schema-automatically.mdx'; import LocalOnly from '/snippets/local-only-escape.mdx';

The SDK is distributed via pub.dev Refer to the `powersync.dart` repo on GitHub Full API reference for the SDK Gallery of example projects/demo apps built with Flutter and PowerSync Changelog for the SDK

Quickstart

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

πŸ“‚ GitHub Repo https://github.com/powersync-community/flutter-powersync-supabase

SDK Features

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

Installation

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

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 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 (or legacy Sync Rules), 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: 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).

The types available are text, integer and real. These should map directly to the values produced by your Sync Streams (or legacy Sync Rules). 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.

Example:

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. PowerSync streams changes from your backend source database into the client-side SQLite database, based on your Sync Streams (or legacy Sync Rules). 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:

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, call the connect() method to sync data with your backend. This method requires the backend connector that will be created in the next step.

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

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

class _DemoAppState extends State<DemoApp> {
  @override
  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-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 - 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 for details, and Authentication Setup for instructions on how the credentials should be generated.
  2. PowerSyncBackendConnector.uploadData - This method will be automatically invoked by the PowerSync Client SDK whenever it needs to upload client-side writes to your app backend via your backend API. Therefore, in your implementation, you need to define how your backend API is called. See When uploadData() is Called for details on triggers, throttling, and retry behavior, and Writing Client Changes for considerations on the app backend implementation.

Example:

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:

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

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

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.

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.

Mutations (PowerSync.execute)

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

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 page.

ORM Support

See ORM Support for details.

Troubleshooting

See Troubleshooting for pointers to debug common issues.

Supported Platforms

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

flutter pub upgrade powersync