### Install PocketBase Dart SDK Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Instructions for adding the PocketBase Dart SDK to your project's dependencies using `dart pub add` or `flutter pub add`. ```sh dart pub add pocketbase # or with Flutter: flutter pub add pocketbase ``` -------------------------------- ### Install PocketBase Dart SDK Source: https://context7.com/pocketbase/dart-sdk/llms.txt Add the PocketBase Dart SDK to your project's dependencies using the Dart or Flutter package manager. ```bash # Dart dart pub add pocketbase # Flutter flutter pub add pocketbase ``` -------------------------------- ### PocketBase Dart SDK Development Commands Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides essential commands for developing with the PocketBase Dart SDK, including running unit tests, viewing documentation locally, executing example code, and generating serializable artifacts. ```shell # run the unit tests dart test # view dartdoc locally dart doc # run the example dart run example/example.dart # generate the DTOs json serializable artifacts dart run build_runner build ``` -------------------------------- ### Upload File with Data (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Example of uploading a file along with other regular form fields to a PocketBase collection using `http.MultipartFile`. ```dart import 'package:http/http.dart' as http; import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); pb.collection('example').create( body: { 'title': 'Hello world!', // ... any other regular field }, files: [ http.MultipartFile.fromString( 'document', // the name of the file field 'example content...', filename: 'example_document.txt', ), ], ).then((record) { print(record.id); print(record.get('title')); }); ``` -------------------------------- ### Manage PocketBase Settings in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt This Dart code example illustrates how to read and update application settings in PocketBase, requiring superuser authentication. It covers fetching all settings, updating specific configurations like app name and URL, testing S3 storage and email configurations, and generating an Apple OAuth2 client secret. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as superuser await pb.collection('_superusers').authWithPassword('admin@example.com', 'password'); // Get all settings final settings = await pb.settings.getAll(); print('App name: ${settings["meta"]["appName"]}'); print('SMTP enabled: ${settings["smtp"]["enabled"]}'); // Update settings await pb.settings.update(body: { 'meta': { 'appName': 'My App', 'appURL': 'https://myapp.com', }, }); // Test S3 storage connection await pb.settings.testS3(body: {'filesystem': 'storage'}); // Test email configuration await pb.settings.testEmail('test@example.com', 'verification'); // Generate Apple OAuth2 client secret final secret = await pb.settings.generateAppleClientSecret( 'your.client.id', 'TEAM_ID', 'KEY_ID', '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----', 31536000, // Duration in seconds (1 year) ); print('Apple client secret: $secret'); ``` -------------------------------- ### Password Reset and Email Verification Flows in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Provides code examples for handling password reset and email verification processes. It covers requesting resets and verification, confirming them with tokens, and managing email change requests and confirmations, ensuring secure user account management. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Request password reset await pb.collection('users').requestPasswordReset('user@example.com'); print('Password reset email sent'); // Confirm password reset (user clicks link in email) await pb.collection('users').confirmPasswordReset( 'TOKEN_FROM_EMAIL', 'newpassword123', 'newpassword123', // Confirmation ); print('Password reset confirmed'); // Request email verification await pb.collection('users').requestVerification('user@example.com'); print('Verification email sent'); // Confirm email verification await pb.collection('users').confirmVerification('TOKEN_FROM_EMAIL'); print('Email verified'); // Request email change await pb.collection('users').requestEmailChange('newemail@example.com'); print('Email change confirmation sent'); // Confirm email change await pb.collection('users').confirmEmailChange( 'TOKEN_FROM_EMAIL', 'currentpassword', // User's current password for security ); print('Email changed'); ``` -------------------------------- ### Impersonate Users with PocketBase Dart SDK Source: https://context7.com/pocketbase/dart-sdk/llms.txt Illustrates how superusers can impersonate regular users to perform actions on their behalf. This involves authenticating as a superuser and then using the `impersonate` method to create a temporary client instance for the target user. The example shows fetching posts for the impersonated user. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as superuser await pb.collection('_superusers').authWithPassword('admin@example.com', 'adminpass'); // Impersonate a regular user final userClient = await pb.collection('users').impersonate( 'USER_RECORD_ID', 3600, // Token duration in seconds (0 = collection default) ); // userClient is now authenticated as the specified user final userData = await userClient.collection('posts').getList( filter: 'author = "${userClient.authStore.record?.id}" ', ); print('User\'s posts: ${userData.items.length}'); ``` -------------------------------- ### Handle API Errors with ClientException in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Demonstrates how to catch and handle API errors using PocketBase's ClientException in Dart. It shows how to access detailed error information like URL, status code, response, and original error, and provides examples for specific status codes (404, 400, 403). ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); try { final record = await pb.collection('posts').getOne('invalid_id'); } on ClientException catch (e) { print('URL: ${e.url}'); print('Status code: ${e.statusCode}'); print('Is abort: ${e.isAbort}'); print('Response: ${e.response}'); print('Original error: ${e.originalError}'); // Access specific error details if (e.statusCode == 404) { print('Record not found'); } else if (e.statusCode == 400) { final errors = e.response['data'] as Map?; errors?.forEach((field, error) { print('Field "$field" error: $error'); }); } else if (e.statusCode == 403) { print('Permission denied'); } } // Async/await style with try-catch Future createPost(Map data) async { try { final record = await pb.collection('posts').create(body: data); print('Created: ${record.id}'); } on ClientException catch (e) { if (e.response['data'] != null) { // Validation errors final errors = e.response['data'] as Map; errors.forEach((field, error) { print('Validation error on $field: ${error['message']}'); }); } rethrow; } } // Future-based style with catchError pb.collection('posts').getList().then((result) { print('Success: ${result.items.length} records'); }).catchError((error) { if (error is ClientException) { print('API Error: ${error.statusCode}'); } else { print('Unknown error: $error'); } }); ``` -------------------------------- ### Access PocketBase Server Logs in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt This Dart code demonstrates how to access PocketBase server request logs, which requires superuser authentication. It shows how to retrieve paginated logs with filtering and sorting, fetch a specific log entry by its ID, and get aggregated log statistics. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as superuser await pb.collection('_superusers').authWithPassword('admin@example.com', 'password'); // Get paginated logs final logs = await pb.logs.getList( page: 1, perPage: 50, filter: 'level >= 400', // Only errors (4xx, 5xx) sort: '-created', ); for (final log in logs.items) { print('${log.created}: ${log.method} ${log.url} - ${log.status}'); } // Get a specific log entry final logEntry = await pb.logs.getOne('LOG_ID'); print('Request details: ${logEntry.toJson()}'); // Get log statistics final stats = await pb.logs.getStats(); for (final stat in stats) { print('${stat.date}: ${stat.total} requests'); } ``` -------------------------------- ### Initialize PocketBase and Authenticate User (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Demonstrates how to initialize the PocketBase client with the API endpoint and authenticate a user using their email and password. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); ... // authenticate as regular user final userData = await pb.collection('users').authWithPassword('test@example.com', '123456'); ``` -------------------------------- ### Initialize PocketBase Client in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Create an instance of the PocketBase client to interact with your backend server. Supports basic, optimized, and persistent session initialization. ```dart import 'package:pocketbase/pocketbase.dart'; import 'package:shared_preferences/shared_preferences.dart'; // Basic initialization final pb = PocketBase('http://127.0.0.1:8090'); // With persistent HTTP client for better performance (~10% improvement) final pbOptimized = PocketBase( 'http://127.0.0.1:8090', reuseHTTPClient: true, // Remember to call pb.close() when done lang: 'en-US', // Optional language header ); // With custom auth store for persistent sessions final prefs = await SharedPreferences.getInstance(); final store = AsyncAuthStore( save: (String data) async => prefs.setString('pb_auth', data), initial: prefs.getString('pb_auth'), ); final pbPersistent = PocketBase('http://127.0.0.1:8090', authStore: store); ``` -------------------------------- ### Manage PocketBase Collections with Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Perform CRUD operations on PocketBase collections using the Dart SDK. Requires superuser authentication. Supports listing, getting, creating, updating, truncating, and deleting collections, as well as retrieving scaffold templates. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as superuser await pb.collection('_superusers').authWithPassword('admin@example.com', 'password'); // List all collections final collections = await pb.collections.getFullList(); for (final col in collections) { print('Collection: ${col.name} (${col.type})'); } // Get a single collection final postsCollection = await pb.collections.getOne('posts'); print('Fields: ${postsCollection.fields}'); // Create a new collection final newCollection = await pb.collections.create(body: { 'name': 'articles', 'type': 'base', 'fields': [ {'name': 'title', 'type': 'text', 'required': true}, {'name': 'content', 'type': 'editor'}, {'name': 'published', 'type': 'bool'}, ], }); // Update collection await pb.collections.update('articles', body: { 'fields': [ {'name': 'title', 'type': 'text', 'required': true}, {'name': 'content', 'type': 'editor'}, {'name': 'published', 'type': 'bool'}, {'name': 'views', 'type': 'number'}, // Added field ], }); // Delete all records in a collection (truncate) await pb.collections.truncate('temp_data'); // Delete a collection await pb.collections.delete('old_collection'); // Get scaffolds for new collection creation final scaffolds = await pb.collections.getScaffolds(); print('Base collection template: ${scaffolds["base"]?.toJson()}'); print('Auth collection template: ${scaffolds["auth"]?.toJson()}'); ``` -------------------------------- ### Authenticate with OTP (Email Code) using PocketBase Dart SDK Source: https://context7.com/pocketbase/dart-sdk/llms.txt Enables authentication using one-time passwords sent via email. This is a two-step process: first request an OTP, then authenticate with the received code. It also includes an example for MFA authentication. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Step 1: Request OTP final otpResponse = await pb.collection('users').requestOTP('user@example.com'); print('OTP sent! OTP ID: ${otpResponse.otpId}'); // Step 2: User enters the code received via email final authData = await pb.collection('users').authWithOTP( otpResponse.otpId, '123456', // Code from email ); print('Authenticated via OTP: ${authData.record?.id}'); // MFA (Multi-Factor Authentication) example try { await pb.collection('users').authWithPassword('user@example.com', 'password'); } on ClientException catch (e) { final mfaId = e.response['mfaId']; if (mfaId != null) { // MFA required - authenticate with second factor final otpResponse = await pb.collection('users').requestOTP('user@example.com'); // User enters OTP code... final authData = await pb.collection('users').authWithOTP( otpResponse.otpId, 'OTP_CODE', query: {'mfaId': mfaId}, // Include MFA ID ); print('MFA authentication complete'); } } ``` -------------------------------- ### Manage Authentication State with AsyncAuthStore in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Demonstrates how to set up and use `AsyncAuthStore` for persistent authentication token management across application sessions. It covers initialization with `shared_preferences`, checking authentication status, listening for auth changes, refreshing tokens, and logging out. ```dart import 'package:pocketbase/pocketbase.dart'; import 'package:shared_preferences/shared_preferences.dart'; // Setup persistent auth store final prefs = await SharedPreferences.getInstance(); final store = AsyncAuthStore( save: (String data) async => prefs.setString('pb_auth', data), initial: prefs.getString('pb_auth'), clear: () async => prefs.remove('pb_auth'), ); final pb = PocketBase('http://127.0.0.1:8090', authStore: store); // Check authentication status print('Is authenticated: ${pb.authStore.isValid}'); print('Token: ${pb.authStore.token}'); print('Current user: ${pb.authStore.record?.id}'); // Listen to auth changes pb.authStore.onChange.listen((event) { print('Auth changed!'); print('New token: ${event.token}'); print('New record: ${event.record?.id}'); }); // Refresh auth token final refreshedAuth = await pb.collection('users').authRefresh(); print('Token refreshed: ${refreshedAuth.token}'); // Logout pb.authStore.clear(); print('Logged out: ${pb.authStore.isValid}'); // false ``` -------------------------------- ### Settings API Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides endpoints for managing application settings, including retrieving all settings, updating them in bulk, testing S3 storage connections, sending test emails, and generating Apple OAuth2 client secrets. ```APIDOC ## SettingsService ### Description Provides endpoints for managing application settings. ### Method GET ### Endpoint /api/settings ### Parameters #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Returns a map with all available app settings. pb.settings.getAll({query, headers}); ``` ### Response #### Success Response (200) - **Map** - A map containing all available app settings. #### Response Example ```json { "someSetting": "value", "anotherSetting": 123 } ``` --- ### Description Bulk updates app settings. ### Method PATCH ### Endpoint /api/settings ### Parameters #### Request Body - **body** (Map) - Required - The settings to update. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Bulk updates app settings. pb.settings.update({body: {"someSetting": "new value"}, query, headers}); ``` ### Response #### Success Response (200) - **Map** - The updated settings. #### Response Example ```json { "someSetting": "new value", "anotherSetting": 123 } ``` --- ### Description Performs a S3 storage connection test. ### Method POST ### Endpoint /api/settings/test-s3 ### Parameters #### Request Body - **body** (Map) - Required - S3 connection details. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Performs a S3 storage connection test. pb.settings.testS3({body: {"bucket": "my-bucket", "region": "us-east-1"}, query, headers}); ``` ### Response #### Success Response (200) - **bool** - True if the connection test is successful, false otherwise. #### Response Example ```json true ``` --- ### Description Sends a test email (verification, password-reset, email-change). ### Method POST ### Endpoint /api/settings/test-email ### Parameters #### Path Parameters - **toEmail** (String) - Required - The recipient's email address. - **template** (String) - Required - The email template to use. #### Request Body - **collection** (String) - Optional - The collection ID for the email template. - **body** (Map) - Optional - Additional data for the email template. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Sends a test email (verification, password-reset, email-change). pb.settings.testEmail('test@example.com', 'verification', {collection: 'myCollectionId', body: {"name": "User"}, query, headers}); ``` ### Response #### Success Response (200) - **bool** - True if the test email was sent successfully, false otherwise. #### Response Example ```json true ``` --- ### Description Generates a new Apple OAuth2 client secret. ### Method POST ### Endpoint /api/settings/apple-client-secret ### Parameters #### Path Parameters - **clientId** (String) - Required - The Apple OAuth2 client ID. - **teamId** (String) - Required - The Apple developer team ID. - **keyId** (String) - Required - The Apple private key ID. - **privateKey** (String) - Required - The Apple private key content. - **duration** (int) - Required - The duration for which the secret is valid (in seconds). #### Request Body - **body** (Map) - Optional - Additional data for the request. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Generates a new Apple OAuth2 client secret. pb.settings.generateAppleClientSecret('CLIENT_ID', 'TEAM_ID', 'KEY_ID', '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----', 3600, {body, query, headers}); ``` ### Response #### Success Response (200) - **String** - The generated client secret. #### Response Example ```json "your_generated_client_secret" ``` ``` -------------------------------- ### Manage PocketBase Settings (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides methods to retrieve all app settings, perform bulk updates, test S3 storage connections, send test emails, and generate Apple OAuth2 client secrets. ```dart // Returns a map with all available app settings. pb.settings.getAll({query, headers}); // Bulk updates app settings. pb.settings.update({body, query, headers}); // Performs a S3 storage connection test. pb.settings.testS3({body, query, headers}); // Sends a test email (verification, password-reset, email-change). pb.settings.testEmail(toEmail, template, {collection, body, query, headers}); // Generates a new Apple OAuth2 client secret. pb.settings.generateAppleClientSecret(clientId, teamId, keyId, privateKey, duration, {body, query, headers}); ``` -------------------------------- ### List and Filter Records (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Shows how to fetch a list of records from a collection, applying pagination, filtering, sorting, and expansion of related fields. ```dart // list and filter "example" collection records final result = await pb.collection('example').getList( page: 1, perPage: 20, filter: 'status = true && created >= "2022-08-01"', sort: '-created', expand: 'someRelField', ); ``` -------------------------------- ### Manage PocketBase Backups (JavaScript) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides functionality to list all backups, create new backups, upload existing backup files, delete backups by key, restore data from backups, and generate download URLs for backups. ```javascript // Returns list with all available backup files. pb.backups.getFullList({query, headers}); // Initializes a new backup. pb.backups.create(basename, {body, query, headers}); // Uploads an existing backup file (_the multipart file key is "file"_). pb.backups.upload(file, {body, query, headers}); // Deletes a single backup by its file key. pb.backups.delete(key, {body, query, headers}); // Initializes an app data restore from an existing backup. pb.backups.restore(key, {body, query, headers}); // Builds a download url for a single existing backup using an // superuser file token and the backup file key. pb.backups.getDownloadURL(token, key, {query}); ``` -------------------------------- ### Manage PocketBase Backups with Dart SDK Source: https://context7.com/pocketbase/dart-sdk/llms.txt Handles PocketBase database backup and restore operations. Requires superuser authentication. Supports listing, creating, uploading, downloading, restoring, and deleting backups. ```dart import 'package:pocketbase/pocketbase.dart'; import 'package:http/http.dart' as http; final pb = PocketBase('http://127.0.0.1:8090'); // Authenticate as superuser await pb.collection('_superusers').authWithPassword('admin@example.com', 'password'); // List all backups final backups = await pb.backups.getFullList(); for (final backup in backups) { print('Backup: ${backup.key} (${backup.size} bytes)'); print('Created: ${backup.modified}'); } // Create a new backup await pb.backups.create('my_backup'); print('Backup created'); // Upload an existing backup file await pb.backups.upload( http.MultipartFile.fromPath('file', '/path/to/backup.zip'), ); // Get backup download URL final token = await pb.files.getToken(); final downloadUrl = pb.backups.getDownloadURL(token, 'backup_file.zip'); print('Download URL: $downloadUrl'); // Restore from backup (WARNING: destructive operation) await pb.backups.restore('backup_file.zip'); print('Backup restored'); // Delete a backup await pb.backups.delete('old_backup.zip'); ``` -------------------------------- ### Subscribe to Realtime Collection Changes (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Illustrates how to subscribe to real-time updates for a specific collection, with options for filtering events. ```dart // subscribe to realtime "example" collection changes pb.collection('example').subscribe("*", (e) { print(e.action); // create, update, delete print(e.record); // the changed record }, filter: "someField > 10"); ``` -------------------------------- ### PocketBase File URL and Token Generation (JavaScript) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides methods to construct absolute URLs for record files and to request private file access tokens. The `getURL` method requires a record object and filename, while `getToken` requests a token for the current authenticated user. ```javascript // Builds and returns an absolute record file url for the provided filename. 🔓 pb.files.getURL(record, filename, {thumb?, token?, query, body, headers}); // Requests a new private file access token for the current auth record. 🔐 pb.files.getToken({query, body, headers}); ``` -------------------------------- ### File URLs and Tokens in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Build URLs for accessing record files and request private file access tokens. PocketBase stores uploaded files and provides URLs to access them. For protected files, you need to include an access token. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Get a record with file fields final post = await pb.collection('posts').getOne('RECORD_ID'); // Build public file URL final thumbnailUrl = pb.files.getURL( post, post.get('thumbnail'), // Filename stored in the record ); print('Thumbnail URL: $thumbnailUrl'); // Build URL with thumbnail transformation final thumbUrl = pb.files.getURL( post, post.get('image'), thumb: '100x100', // Resize to 100x100 ); // Force download disposition final downloadUrl = pb.files.getURL( post, post.get('attachment'), download: true, ); // For protected files, get an access token first final token = await pb.files.getToken(); final protectedUrl = pb.files.getURL( post, post.get('private_doc'), token: token, ); print('Protected URL with token: $protectedUrl'); ``` -------------------------------- ### Realtime Subscriptions and Disconnect Handling (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Enables subscribing to and unsubscribing from realtime events, including managing subscriptions by prefix. It also includes an optional hook for handling disconnect events. ```dart // Initialize the realtime connection (if not already) and register the subscription. // // You can subscribe to the `PB_CONNECT` event if you want to listen to the realtime connection connect/reconnect events. pb.realtime.subscribe(subscription, callback, {filter?, expand?, fields?, query, headers}); // Unsubscribe from a subscription (if empty - unsubscribe from all registered subscriptions). pb.realtime.unsubscribe([subscription = '']); // Unsubscribe from all subscriptions starting with the provided prefix. pb.realtime.unsubscribeByPrefix(subscriptionsPrefix); // An optional hook that is invoked when the realtime client disconnects // either when unsubscribing from all subscriptions or when the connection // was interrupted or closed by the server. // // Note that the realtime client autoreconnect on its own and this hook is // useful only for the cases where you want to apply a special behavior on // server error or after closing the realtime connection. pb.realtime.onDisconnect = (subscriptions) { ... } ``` -------------------------------- ### Backup API Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Manages application backups, including listing, creating, uploading, deleting, restoring, and generating download URLs for backup files. ```APIDOC ## BackupService ### Description Manages application backups. ### Method GET ### Endpoint /api/backups ### Parameters #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```js // Returns list with all available backup files. pb.backups.getFullList({query, headers}); ``` ### Response #### Success Response (200) - **List>** - A list of available backup files. #### Response Example ```json [ { "key": "backup_1678886400_abcdef", "created": "2023-03-15T12:00:00.000Z", "size": 102400 } ] ``` --- ### Description Initializes a new backup. ### Method POST ### Endpoint /api/backups ### Parameters #### Path Parameters - **basename** (String) - Required - The base name for the backup file. #### Request Body - **body** (Map) - Optional - Additional data for the backup request. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```js // Initializes a new backup. pb.backups.create('my_app_backup', {body, query, headers}); ``` ### Response #### Success Response (200) - **Map** - Information about the created backup. #### Response Example ```json { "key": "backup_1678886400_abcdef", "created": "2023-03-15T12:00:00.000Z", "size": 0 } ``` --- ### Description Uploads an existing backup file. ### Method POST ### Endpoint /api/backups/upload ### Parameters #### Path Parameters - **file** (File) - Required - The backup file to upload (multipart file key is "file"). #### Request Body - **body** (Map) - Optional - Additional data for the upload request. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```js // Uploads an existing backup file. final file = File('path/to/your/backup.zip'); pb.backups.upload(file, {body, query, headers}); ``` ### Response #### Success Response (200) - **Map** - Information about the uploaded backup. #### Response Example ```json { "key": "backup_1678886400_abcdef", "created": "2023-03-15T12:00:00.000Z", "size": 102400 } ``` --- ### Description Deletes a single backup by its file key. ### Method DELETE ### Endpoint /api/backups/{key} ### Parameters #### Path Parameters - **key** (String) - Required - The key of the backup file to delete. #### Request Body - **body** (Map) - Optional - Additional data for the delete request. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```js // Deletes a single backup by its file key. pb.backups.delete('backup_1678886400_abcdef', {body, query, headers}); ``` ### Response #### Success Response (200) - **bool** - True if the backup was deleted successfully, false otherwise. #### Response Example ```json true ``` --- ### Description Initializes an app data restore from an existing backup. ### Method POST ### Endpoint /api/backups/{key}/restore ### Parameters #### Path Parameters - **key** (String) - Required - The key of the backup file to restore from. #### Request Body - **body** (Map) - Optional - Additional data for the restore request. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```js // Initializes an app data restore from an existing backup. pb.backups.restore('backup_1678886400_abcdef', {body, query, headers}); ``` ### Response #### Success Response (200) - **bool** - True if the restore process was initiated successfully, false otherwise. #### Response Example ```json true ``` --- ### Description Builds a download URL for a single existing backup. ### Method GET ### Endpoint /api/backups/{key}/download ### Parameters #### Path Parameters - **token** (String) - Required - A superuser file token. - **key** (String) - Required - The key of the backup file to download. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. ### Request Example ```js // Builds a download url for a single existing backup. pb.backups.getDownloadURL('SUPERUSER_TOKEN', 'backup_1678886400_abcdef', {query}); ``` ### Response #### Success Response (200) - **String** - The download URL for the backup file. #### Response Example ```json "https://your-pocketbase-url.com/api/backups/backup_1678886400_abcdef?token=SUPERUSER_TOKEN" ``` ``` -------------------------------- ### Enable HTTP Client Reuse in Dart SDK for Performance Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Demonstrates how to enable HTTP client reuse in the PocketBase Dart SDK using the `reuseHTTPClient` constructor option. This can improve performance for multiple requests but requires calling `pb.close()` when done. ```dart import 'package:pocketbase/pocketbase.dart'; // enable the reuseHTTPClient option final pb = PocketBase('http://127.0.0.1:8090', reuseHTTPClient: true); ... // after close() no further requests can be made with this instance pb.close(); ``` -------------------------------- ### Fetch All Records (getFullList) in Dart Source: https://context7.com/pocketbase/dart-sdk/llms.txt Retrieve all records from a PocketBase collection at once using internal batch requests. Useful for fetching complete datasets without manual pagination. ```dart import 'package:pocketbase/pocketbase.dart'; final pb = PocketBase('http://127.0.0.1:8090'); // Fetch all records matching the filter final allPosts = await pb.collection('posts').getFullList( batch: 500, // Records per batch request filter: 'published = true', sort: '-created', expand: 'author', ); print('Fetched ${allPosts.length} published posts'); for (final post in allPosts) { print('${post.get("title")} by ${post.get("expand.author.name")}'); } ``` -------------------------------- ### Manage Authentication State with AuthStore in Dart Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Explains the use of the AuthStore service in the PocketBase Dart SDK for managing authentication tokens and records. It covers saving, clearing, listening to changes, and persistence options. ```dart AuthStore { token: String // Getter for the stored auth token record: RecordModel|null // Getter for the stored auth RecordModel isValid bool // Getter to loosely check if the store has an existing and unexpired token onChange Stream // Stream that gets triggered on each auth store change // methods save(token, record) // update the store with the new auth data clear() // clears the current auth store state } pb.authStore.clear() pb.authStore.onChange.listen((e) { print(e.token); print(e.record); }); ``` -------------------------------- ### Access and Cast Record Data (Dart) Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Demonstrates how to retrieve a single record and access its fields, casting them to their appropriate types using `record.get()`. ```dart final record = await pb.collection('example').getOne('RECORD_ID'); final options = record.get>('options'); final email = record.get('email'); final status = record.get('status'); final total = record.get('total'); final price = record.get('price'); final nested1 = record.get('expand.user', null); final nested2 = record.get('expand.user.title', 'N/A'); ``` -------------------------------- ### LogService API Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Provides access to application logs and statistics. ```APIDOC ## LogService API ### Description This service allows you to retrieve and inspect application logs, as well as view log statistics. ### Method GET ### Endpoint `/api/logs/*` ### Parameters - **`getList(options)`**: Optional `page`, `perPage`, `filter`, `sort`, `query`, `headers`. - **`getOne(id, options)`**: Requires `id`. Optional `query`, `headers`. - **`getStats(options)`**: Optional `query`, `headers`. ### Request Example ```dart // Get a paginated list of logs pb.logs.getList(page: 1, perPage: 20, filter: 'level="error"'); // Get log statistics pb.logs.getStats(); ``` ### Response - **`getList` Success Response**: Paginated list of log entries. - **`getOne` Success Response**: A single log entry object. - **`getStats` Success Response**: An object containing log statistics. - **Error Response**: Standard PocketBase error format. ``` -------------------------------- ### Authenticate with OAuth2 (All-in-One) using PocketBase Dart SDK Source: https://context7.com/pocketbase/dart-sdk/llms.txt Handles the OAuth2 authentication flow without custom redirects or page reloads, using a realtime subscription for callbacks. Requires the redirect URL to be configured in the OAuth2 provider's dashboard. It opens the OAuth2 URL in a browser and handles potential `ClientException`. ```dart import 'package:pocketbase/pocketbase.dart'; import 'package:url_launcher/url_launcher.dart'; final pb = PocketBase('http://127.0.0.1:8090'); try { final authData = await pb.collection('users').authWithOAuth2( 'google', // Provider name: google, github, facebook, etc. (url) async { // Open the OAuth2 URL in a browser/webview await launchUrl(url); }, scopes: ['email', 'profile'], createData: { // Additional fields when creating a new user 'name': 'Default Name', }, ); print('OAuth2 success!'); print('User: ${authData.record?.get("email")}'); print('Provider: ${authData.meta?["provider"]}'); // Access OAuth2 metadata final avatarURL = authData.meta?['avatarURL']; final rawUser = authData.meta?['rawUser']; } on ClientException catch (e) { print('OAuth2 failed: ${e.originalError}'); } ``` -------------------------------- ### RecordService - Realtime Subscriptions Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Handles subscribing to and unsubscribing from realtime changes within a collection. ```APIDOC ## RecordService - Realtime Subscriptions ### Description Allows clients to subscribe to realtime updates for records in a collection and manage these subscriptions. ### Methods #### Subscribe - **Method**: SUBSCRIBE - **Endpoint**: `/api/collections/{collectionIdOrName}/realtime` - **Description**: Subscribes to realtime changes for a specific topic (e.g., a record ID or '*'). - **Parameters**: - `topic` (string) - Required - The topic to subscribe to (e.g., `recordId` or `*` for all changes). - `callback` (function) - Required - The function to call when a message is received. - `filter` (string) - Optional - Filtering criteria for subscribed messages. - `expand` (string) - Optional - Fields to expand in the message data. - `fields` (string) - Optional - Specific fields to include in the message data. - `query` (object) - Optional - Additional query parameters. - `headers` (object) - Optional - Custom headers for the subscription request. - **Returns**: An `UnsubscribeFunc` to remove the specific subscription. #### Unsubscribe - **Method**: UNSUBSCRIBE - **Endpoint**: `/api/collections/{collectionIdOrName}/realtime` - **Description**: Unsubscribes from realtime changes for a specified topic. - **Parameters**: - `topic` (string) - Optional - The topic to unsubscribe from. If not provided, all collection subscriptions are removed. ### Usage Example (Subscribe) ```dart void handleRealtimeUpdate(data) { print('Realtime update received: $data'); } // Subscribe to all changes in a collection final unsubscribe = pb.collection('my_collection').subscribe('*', handleRealtimeUpdate); // To unsubscribe later: unsubscribe(); // Subscribe to changes for a specific record final recordUnsubscribe = pb.collection('my_collection').subscribe('recordId123', handleRealtimeUpdate); // To unsubscribe later: recordUnsubscribe(); // Unsubscribe from all subscriptions for the collection pb.collection('my_collection').unsubscribe(); ``` ``` -------------------------------- ### Implement Persistent AuthStore with AsyncAuthStore and SharedPreferences in Dart Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Shows how to create a persistent authentication store using AsyncAuthStore combined with Flutter's SharedPreferences. This ensures auth state is maintained across app sessions. ```dart import 'package:shared_preferences/shared_preferences.dart'; import 'package:pocketbase/pocketbase.dart'; final prefs = await SharedPreferences.getInstance(); final store = AsyncAuthStore( save: (String data) async => prefs.setString('pb_auth', data), initial: prefs.getString('pb_auth'), ); final pb = PocketBase('http://example.com', authStore: store); ``` -------------------------------- ### Realtime API Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Manages real-time subscriptions and connection events for the application. Allows subscribing to specific events, unsubscribing, and handling disconnections. ```APIDOC ## RealtimeService ### Description Manages real-time subscriptions and connection events. ### Method POST ### Endpoint /api/realtime/subscribe ### Parameters #### Path Parameters - **subscription** (String) - Required - The subscription identifier. - **callback** (Function) - Required - The callback function to execute when an event occurs. #### Query Parameters - **filter** (String) - Optional - A filter for the subscription. - **expand** (List) - Optional - Fields to expand in the subscription data. - **fields** (List) - Optional - Specific fields to include in the subscription data. - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Initialize the realtime connection (if not already) and register the subscription. pb.realtime.subscribe('mySubscription', (data) { print('Received data: $data'); }, filter: 'someField = "value"', expand: ['relationField'], fields: ['id', 'name'], query, headers); ``` ### Response #### Success Response (200) - **void** - The subscription is registered. --- ### Description Unsubscribes from a specific subscription or all subscriptions if none is provided. ### Method POST ### Endpoint /api/realtime/unsubscribe ### Parameters #### Path Parameters - **subscription** (String) - Optional - The subscription identifier to unsubscribe from. If empty, unsubscribes from all. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Unsubscribe from a specific subscription. pb.realtime.unsubscribe('mySubscription'); // Unsubscribe from all subscriptions. pb.realtime.unsubscribe(); ``` ### Response #### Success Response (200) - **void** - The subscription(s) have been unsubscribed. --- ### Description Unsubscribes from all subscriptions starting with the provided prefix. ### Method POST ### Endpoint /api/realtime/unsubscribe-by-prefix ### Parameters #### Path Parameters - **subscriptionsPrefix** (String) - Required - The prefix of subscriptions to unsubscribe from. #### Query Parameters - **query** (dynamic) - Optional - Query parameters for the request. - **headers** (Map) - Optional - Custom headers for the request. ### Request Example ```dart // Unsubscribe from all subscriptions starting with 'user_'. pb.realtime.unsubscribeByPrefix('user_'); ``` ### Response #### Success Response (200) - **void** - The subscriptions have been unsubscribed. --- ### Description An optional hook that is invoked when the realtime client disconnects. ### Method N/A (Callback Hook) ### Endpoint N/A ### Parameters #### Callback Parameters - **subscriptions** (List) - A list of active subscriptions when disconnection occurs. ### Request Example ```dart pb.realtime.onDisconnect = (subscriptions) { print('Realtime client disconnected. Active subscriptions: $subscriptions'); // Handle disconnection logic here }; ``` ### Response N/A ``` -------------------------------- ### FileService API Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Handles operations related to file storage and retrieval within PocketBase. ```APIDOC ## FileService API ### Description Provides methods for interacting with file storage, including generating file URLs and obtaining private file access tokens. ### Method GET, POST ### Endpoint `/api/files/*` ### Parameters - **`getURL(record, filename)`**: Requires `record` object and `filename`. Optional parameters include `thumb`, `token`, `query`, `body`, `headers`. - **`getToken()`**: Optional parameters include `query`, `body`, `headers`. ### Request Example ```dart // Get file URL pb.files.getURL(record, 'my_file.jpg'); // Get file token pb.files.getToken(); ``` ### Response - **`getURL` Success Response**: String representing the absolute file URL. - **`getToken` Success Response**: String representing a private file access token. - **Error Response**: Standard PocketBase error format. ``` -------------------------------- ### PocketBase Dart SDK: RecordService Realtime Subscriptions Source: https://github.com/pocketbase/dart-sdk/blob/master/README.md Enables real-time event handling for PocketBase collections. You can subscribe to changes on specific topics (like a record ID or all changes using '*') and receive real-time updates via a callback function. The SDK provides methods to subscribe to topics and unsubscribe from them, either individually or all subscriptions for a given topic. ```dart pb.collection(collectionIdOrName).subscribe(topic, callback, {filter?, expand?, fields?, query, headers}); pb.collection(collectionIdOrName).unsubscribe([topic]); ```