-
Notifications
You must be signed in to change notification settings - Fork 29
Open
Description
I am trying to setup a simple one way sync from the powersync service to client in flutter sdk.
below is my connector
import 'package:powersync/powersync.dart';
class MyBackendConnector extends PowerSyncBackendConnector {
@override
Future<PowerSyncCredentials?> fetchCredentials() async {
return PowerSyncCredentials(
endpoint: 'https://powersync.dev.merasamaaj.com',
token: '[my valid token]',
userId: "2437",
);
}
@override
Future<void> uploadData(PowerSyncDatabase db) async {
// No-op: not pushing changes in this example
}
}
DB init
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import '../models/schema.dart';
late PowerSyncDatabase db;
Future<void> openDatabase() async {
final dir = await getApplicationSupportDirectory();
final path = join(dir.path, 'powersync-demo.db');
db = PowerSyncDatabase(schema: schema, path: path);
await db.initialize();
}
Main.dart
import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart' hide Column;
import 'powersync/my_backend_connector.dart';
import 'powersync/powersync.dart';
import 'widgets/list_widget.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await openDatabase();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PowerSync Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _connected = false;
SyncStatus? _syncStatus;
List<Map<String, dynamic>> _data = [];
@override
void initState() {
super.initState() ;
db.connect(connector: MyBackendConnector() ) .then((_) {
setState(() => _connected = true) ;
_loadData() ; // Load data after connection
}) ;
// Listen to sync status
db.statusStream.listen((status) {
print('PowerSync Status Changed:') ;
print(' Connected: ${status.connected}') ;
print(' Has Synced: ${status.hasSynced}') ;
print(' Last Sync Timestamp: ${status.lastSyncedAt}') ;
setState(() => _syncStatus = status) ;
// Reload data when sync status changes
if (status.connected) {
_loadData() ;
}
}) ;
}
Future<void> _loadData() async {
try {
// Query your synced tables - adjust table names based on your schema
final results = await db.execute('SELECT * FROM countries') ;
setState(() {
_data = results;
}) ;
print('Loaded ${results.length} records from database') ;
} catch (e) {
print('Error loading data: $e') ;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Countries") ) ,
body: Column(
children: [
if (_syncStatus != null)
Padding(
padding: const EdgeInsets.all(8.0) ,
child: Text(
'Status: ${_syncStatus!.connected ? "Connected" : "Disconnected"} | '
'Synced: ${_syncStatus!.hasSynced! ? "✅" : "❌"}',
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold) ,
) ,
) ,
const Divider(height: 1) ,
// Display the synced data
Expanded(
child: _data.isEmpty
? const Center(child: Text('No data available') )
: ListView.builder(
itemCount: _data.length,
itemBuilder: (context, index) {
final item = _data[index];
return ListTile(
title: Text(item['name'] ?? 'Unknown') , // Adjust field names
subtitle: Text(item['id'] ?? '') ,
) ;
},
) ,
) ,
],
) ,
) ;
}
}
Below are the logs recieved:
Restarted application in 831ms.
I/flutter (20197): Loaded 0 records from database
I/flutter (20197): PowerSync Status Changed:
I/flutter (20197): Connected: false
I/flutter (20197): Has Synced: false
I/flutter (20197): Last Sync Timestamp: null
I/flutter (20197): [PowerSync] FINE: 2025-07-17 18:31:24.647319: Credentials: PowerSyncCredentials<endpoint: https://powersync.dev.merasamaaj.com userId: 2437 expiresAt: null>
I/flutter (20197): PowerSync Status Changed:
I/flutter (20197): Connected: true
I/flutter (20197): Has Synced: false
I/flutter (20197): Last Sync Timestamp: null
I/flutter (20197): Loaded 0 records from database
I/flutter (20197): PowerSync Status Changed:
I/flutter (20197): Connected: true
I/flutter (20197): Has Synced: false
I/flutter (20197): Last Sync Timestamp: null
I/flutter (20197): Loaded 0 records from database
Note: I am able to connect with the same token and url and retrieve my countries list data on the diagnostic tool running locally on my system.
Schema:
import 'package:powersync/powersync.dart';
const schema = Schema([
Table('countries', [
Column.text('name'),
Column.text('numeric_code'),
], indexes: [
Index('cnt_nm', [IndexedColumn('name')]),
])
]);
Backend DB Table structure:
create table public.countries (
id serial not null,
name character varying(250) not null,
numeric_code character varying(250) null,
constraint pk_countries primary key (id)
) TABLESPACE pg_default;
create index IF not exists cnt_nm on public.countries using btree (name) TABLESPACE pg_default;
My sync rule is also a globa_bucket with query select * from countries
Server logs from self hosted powersync service:
INF POST /sync/stream | client_id=8efb803e-ecee-4237-9e9a-f74d8440e86e duration_ms=282548 method=POST path=/sync/stream rid=h/0198185c-e9f3-71ed-9f1b-e67d7329fad0 route=/sync/stream status=200 timestamp=2025-07-17T12:34:41.703Z user_agent=powersync-dart-core/1.4.1 Dart/3.8.1 android user_id=b29a2678-91c3-406a-9109-2cb99bcc6a01
INF New checkpoint: 258 | write: null | buckets: 1 ["global[]"] | buckets=1 checkpoint=258 client_id=8efb803e-ecee-4237-9e9a-f74d8440e86e rid=h/01981861-413a-74eb-9305-2f8ecec23610 route=/sync/stream timestamp=2025-07-17T12:34:43.646Z user_agent=powersync-dart-core/1.4.1 Dart/3.8.1 android user_id=b29a2678-91c3-406a-9109-2cb99bcc6a01
Hope these details help!
Ive been stuck on this since a while now
Metadata
Metadata
Assignees
Labels
No labels