plexivo_client
The backend for your Flutter app, on PostgreSQL. Plexivo Postgres is a Backend-as-a-Service — a Firebase alternative — that gives your Flutter and Dart apps a real PostgreSQL database with authentication, a Data API, realtime, GraphQL with live queries, and Plexivo Functions. This is its client, null-safe and pure Dart: Android, iOS, web, macOS, Windows, Linux and servers.
dependencies:
plexivo_client: ^0.3.0
import 'package:plexivo_client/plexivo_client.dart';
final db = PlexivoClient(projectUrl, publishableKey);
await db.signInWithPassword(email: email, password: password);
final todos = await db.from('todos').where('done', false).order('created_at', 'desc');
Row-level security in your database decides what every request may read and write, so your app talks to its data directly — no API server to write.
Docs: plexivo.io/docs · API reference: the API tab on pub.dev · Examples: example/main.dart and a Flutter app
Quick start
Five minutes from nothing to a working backend.
-
Create a Plexivo Postgres in the console and turn on its Data API.
-
Copy two values from the database's Connect tab: the Project URL and the publishable key. The secret key is shown once when you turn the Data API on — keep it for servers only.
-
Create a table with a policy. A table is visible to apps only when row-level security is on and a policy allows access. Run
example/schema.sqlonce — withpsqlthroughplexivo db connect YOUR_DATABASE, or from your machine with the secret key:PLEXIVO_URL=https://… PLEXIVO_SECRET_KEY=… dart run example/setup.dartThe heart of it:
CREATE TABLE todos ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, owner_id uuid NOT NULL DEFAULT auth.uid(), title text NOT NULL, done boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE todos ENABLE ROW LEVEL SECURITY; CREATE POLICY own_todos ON todos FOR ALL TO authenticated USING (owner_id = auth.uid()) WITH CHECK (owner_id = auth.uid()); GRANT SELECT, INSERT, UPDATE, DELETE ON todos TO authenticated; -
Connect.
final db = PlexivoClient('https://…/client/v1/your-project', 'your-publishable-key'); await db.signUp(email: 'ada@example.com', password: 'a long password'); await db.from('todos').create({'title': 'Ship it'}); print(await db.from('todos').where('done', false));
In a Flutter app, pass the values with --dart-define rather than in source. For Flutter web, add the app's origin to the Data API's allowed origins. Switch Realtime on per table in the console for live updates.
Authentication
Your app's own users, with sessions that refresh themselves. Policies see the signed-in user as auth.uid().
await db.signUp(email: email, password: password);
await db.signInWithPassword(email: email, password: password);
// Passwordless: an email code
await db.signInWithOtp(email);
await db.verifyOtp(email: email, token: code);
// Guests who become accounts later, keeping their id and rows
await db.signInAnonymously();
await db.linkEmail(email: email, password: password);
// Google, GitHub or Microsoft (OAuth with PKCE): open the URL, then exchange the code
final url = db.getOAuthSignInUrl(provider: 'google', redirectTo: 'myapp://auth');
await db.exchangeCodeForSession(codeFromRedirect);
// The session and the user
db.session; // Map<String, dynamic>? — null when signed out
await db.getUser();
db.authStateChanges.listen((state) {
// state.event: SIGNED_UP, SIGNED_IN, TOKEN_REFRESHED, USER_UPDATED, SIGNED_OUT, …
});
// Devices, passwords, two-factor
await db.listSessions(); // revokeSession(id) signs one out
await db.resetPasswordForEmail(email);
await db.verifyPasswordRecovery(email: email, code: code, newPassword: newPassword);
await db.mfa.enroll(); // TOTP
await db.mfa.verify(code);
await db.signOut(); // this device; signOut(allSessions: true) for all
To keep users signed in across launches, save state.session from authStateChanges in encrypted storage (for example flutter_secure_storage) and pass it back as PlexivoClient(url, key, initialSession: saved). An expired access token is refreshed once and the request retried.
Organisations for your users — roles, members, invitations — are built in: db.orgs.create, invite, acceptInvitation, members, setRole.
Data
Every table your policies allow, with filters, ordering and pages. Awaiting a query runs it; results are a PlexivoResult — a List<Map<String, dynamic>> that also carries count.
// Create — one row back, or many
final todo = await db.from('todos').create({'title': 'Buy milk'});
await db.from('todos').createMany([{'title': 'Book flights'}, {'title': 'Call mum'}]);
// Read — filters, order, pagination
final open = await db.from('todos')
.select('id, title, done')
.where('done', false) // = ; or where('likes', '>', 10)
.whereILike('title', '%milk%')
.whereIn('id', [1, 2, 3])
.order('created_at', 'desc')
.limit(20)
.offset(40); // or .page(3, 20), or .range(40, 59)
final page = await db.from('todos').paginate(page: 2, perPage: 20);
// page.data, page.total, page.totalPages
final one = await db.from('todos').first(todo['id']); // RecordNotFoundException if absent
final total = await db.from('todos').count();
// Update and delete — always with a filter
await db.from('todos').where('id', todo['id']).update({'done': true});
await db.from('todos').where('done', true).delete();
// Upsert
await db.from('settings').upsert({'key': 'theme', 'value': 'dark'}, onConflict: 'key');
Supabase-style names work too: select('*', 'exact'), eq, neq, gt, ilike, or('a.eq.1,b.gt.2'), match, textSearch, range, single(), maybeSingle(). in and is are Dart keywords, so they are inFilter and isFilter.
More: orWhere, whereNot, whereBetween, whereNull, whereJson, whereContains, whereSearch, whereHas, aggregates (sum, avg, min, max, aggregate, groupBy().having()), findInBatches and await for (final row in query.each()). An update or delete without a filter is refused (missing_where); allowGlobalUpdate() opts in. Call a function exposed with COMMENT ON FUNCTION … IS '@expose' with await db.rpc('fn_name', {'arg': 1}).
Realtime
Row changes as a Stream, as each subscriber is allowed to read them, plus rooms for broadcast and presence. Switch Realtime on for a table in the console first.
final feed = db.channel('changes:messages', 'room=eq.lobby')..subscribe();
feed.changes.listen((PlexivoChange change) {
print('${change.type} ${change.record}'); // insert | update | delete
});
feed.errors.listen(print); // table_not_exposed, sign_in_required, …
final room = db.channel('room:lobby', null, {'name': 'Asha'})..subscribe();
await room.ready();
room.on('typing').listen((payload) => print(payload));
room.presence.listen((p) => print(p.state));
room.sendBroadcast('typing', {'name': 'Asha'});
await feed.unsubscribe();
Channels reconnect on their own. ready() completes with a PlexivoException if the server refuses the join.
GraphQL and live queries
A GraphQL API generated from your schema — exactly as wide as your policies allow.
final result = await db.graphql(
r'query Open($limit: Int) { todos(where: {done: {eq: false}}, orderBy: [{created_at: DESC}], limit: $limit) { id title } }',
variables: {'limit': 10},
);
final todos = (result['data'] as Map)['todos'];
await db.graphql('mutation { insertTodosOne(object: {title: "From GraphQL"}) { id } }');
// A live query: the answer now, and again whenever a row it reads changes
final stop = await db.graphqlSubscribe('subscription { todosAggregate { count } }', (r) => print(r['data']));
await stop();
For each table: todos, todosByPk, todosAggregate, insertTodos, insertTodosOne, updateTodos, updateTodosByPk, deleteTodos, deleteTodosByPk. persisted: true sends only a hash after the first call. Live queries need Realtime on for the tables they read.
Plexivo Functions
Your server-side code, beside your data. Deploy from the database's Functions tab (example/functions/hello.js); call it with the user's identity attached.
final res = await db.functions.invoke('hello', body: {'name': 'Ada'});
print(res.data['message']); // JSON is decoded for you; res.status, res.headers
await db.functions.invoke('orders', method: 'GET', path: 'recent', query: {'limit': 10});
Files
final object = await db.storage.upload('avatars/me.png', bytes, contentType: 'image/png');
final file = await db.storage.download(object['id'] as String); // file.bytes, file.contentType
await db.storage.remove(object['id'] as String);
Errors and null safety
Every API failure is a PlexivoException with statusCode, code, message, hint, sqlstate and a traceId to quote to support. Lookups that must find a row throw RecordNotFoundException; the …OrNull and maybe… variants return null instead.
try {
await db.from('profiles').create({'username': 'ada'});
} on PlexivoException catch (e) {
if (e.isUniqueViolation) return showMessage('That username is taken.');
if (e.isPermissionDenied) return showMessage('You can’t do that.');
rethrow;
}
final maybe = await db.from('todos').firstOrNull(42); // Map<String, dynamic>?
Common codes: invalid_credentials, email_taken, weak_password, unique_violation, foreign_key_violation, check_violation, permission_denied, table_not_exposed, missing_where, record_not_found, multiple_rows, sign_in_required, function_not_found. A 429 means slow down: wait for its Retry-After.
Security
- Row-level security is the gate. A table reaches apps only with row-level security on and at least one policy, written for
anon(signed out) andauthenticated(signed in) withauth.uid(),auth.role(),auth.jwt()andauth.email(). - The publishable key is public. It is safe in an app and can do only what your policies allow.
- Never ship the secret key. It bypasses row-level security and runs raw SQL. Keep it on servers — never in a Flutter app, which anyone can unpack. If it leaks, rotate it from the database's Authentication tab.
- Store sessions encrypted on the device.
Coming from Firebase
| Firebase (FlutterFire) | plexivo_client |
|---|---|
FirebaseAuth.createUserWithEmailAndPassword, signInWithEmailAndPassword |
signUp, signInWithPassword |
authStateChanges(), signOut() |
authStateChanges, signOut() |
signInAnonymously, linkWithCredential |
signInAnonymously, linkEmail |
| Google / GitHub / Microsoft providers | getOAuthSignInUrl + exchangeCodeForSession |
| Firestore collection / document | PostgreSQL table / row |
add, set, update, delete |
create, upsert / save, update, delete |
where, orderBy, limit, startAfter |
.where(), .order(), .limit(), .paginate() / .range() |
count(), sum(), average() |
.count(), .sum(), .avg(), .aggregate() |
snapshots() |
channel('changes:table').changes or graphqlSubscribe |
runTransaction, WriteBatch |
db.transaction() |
| Security Rules | Row-level security policies, in SQL |
Cloud Functions, httpsCallable |
Plexivo Functions, functions.invoke() |
| Cloud Storage | storage.upload(), storage.download() |
What you gain: SQL joins, constraints and transactions; GraphQL for free; your data in standard PostgreSQL you can query, back up and move.
Models, relations and transactions
Declare a table once; queries then understand its relations, hooks, scopes and soft deletes — in the style of GORM.
final posts = db.model('posts',
softDelete: 'deleted_at',
relations: {
'author': const PlexivoRelation.belongsTo('authors', foreignKey: 'author_id'),
'comments': const PlexivoRelation.hasMany('comments', foreignKey: 'post_id'),
'tags': const PlexivoRelation.manyToMany('tags', through: 'post_tags', foreignKey: 'post_id', otherKey: 'tag_id'),
},
scopes: {'popular': (q) => q.where('likes', '>=', 10)},
);
final rows = await posts.query()
.scopes(['popular'])
.preload('author', (PlexivoEmbed a) => a.select('name'))
.withCount('comments');
// All or nothing, in one request; .ref() passes a result to the next step
await db.transaction((tx) {
final author = tx.from('authors').insert({'name': 'Asha'});
tx.from('posts').insert({'title': 'Hi', 'author_id': author.ref('id')});
tx.from('products').where('sku', 'B2').lockForUpdate().find();
});
On a server with the secret key only: raw, exec, sql.transaction, migrator.autoMigrate([...]) and versioned migrate / rollback.
Examples
example/main.dart— auth, todo CRUD, realtime, GraphQL with a live query, and a function call, from the command line:PLEXIVO_URL=… PLEXIVO_PUBLISHABLE_KEY=… dart run example/main.dart.example/flutter_app— a Flutter app: sign-in, a todo list kept in sync across devices, and a realtime chat with a typing indicator.flutter run --dart-define-from-file=dart_defines.json.example/schema.sqlandexample/setup.dart— the tables they use.
No keys live in the code: each example reads your project from the environment or a defines file.
Development
dart test
dart analyze
dart doc
License
Apache-2.0. See LICENSE.
Libraries
- plexivo_client
- Plexivo Postgres for Flutter and Dart.