r/FlutterDev • • Jan 02 '23

Article First Impression of PocketBase

I was testing PocketBase. It's a standalone backend that supports user management with authentication, database storage with realtime updates and file storage. It is backed by Sqlite which is sufficient for small and medium-sided projects.

PocketBase is a single binary that requires no configuration besides setting up an admin account on first launch. It will create folders in the current directory to store its data.

After starting the server, log into the admin UI and create a record collection (a.k.a. table), like for example posts with fields like title and content. Also add an author which is a relation to the predefined users collection. Create yourself a user and some posts. It's that easy.

There is an official Dart client available.

Point it to your server and you're good to go:

final pb = PocketBase('http://127.0.0.1:8090');

To read all posts, you create a collection and ask it for records like so:

final result = await pb.collection('posts').getList();
final records = result.items;

By default, results are paged by chunks of 30 records and the result object will tell you the total number of records (a.k.a. items), the number of pages and which page you requested and which items are in that page. Each item is a RecordModel that has an id and a Map<String, dynamic> with all data. If you like, you can also query the related user record by adding expand: 'author' to the getList() call.

However, to get any result, you either need to be signed in or you have to setup API rules that allow list and view access to anybody. By default, only admin users can access data via API.

Of course, all CRUD operations are supported.

Instead of reading data once, you can subscribe to all changes in a collection or in a certain record. You'll then receive create, update and delete notifications. The Dart API is unfortunately a little bit non-canonical but still easy to work with.

I came up with the following method to make access to a collection a little bit more Firebase-y (and to automatically map data to instances of M):

Stream<List<M>> snapshots() {
  late final StreamController<List<M>> controller;
  Future<void> Function()? unsubscribe;
  final models = <M>[];
  void notify() {
    models.sort();
    controller.add([...models]);
  }

  controller = StreamController<List<M>>(
    onListen: () {
      service.getFullList().then((items) {
        models.clear();
        models.addAll(items.map(fromRecord));
        notify();
      });
      service.subscribe('*', (e) {
        switch (e.action) {
          case 'create':
            final model = fromRecord(e.record!);
            models.add(model);
            notify();
            break;
          case 'update':
            final model = fromRecord(e.record!);
            final id = model.id;
            final i = models.indexWhere((model) => model.id == id);
            if (i != -1) {
              models[i] = model;
            }
            notify();
            break;
          case 'delete':
            final id = e.record!.id;
            models.removeWhere((model) => model.id == id);
            notify();
            break;
        }
      }).then((u) => unsubscribe = u);
    },
    onCancel: () {
      unsubscribe?.call();
      unsubscribe = null;
    },
  );
  return controller.stream;
}

I intent to filter out bogus stream events by comparing all models but haven't done, yet. Currently, it's fast enough. Much faster as Firebase, actually, because my server is local. This is nice for development.

To sign in, simply call authWithPassword (or authWithOAuth2) on the users collection. You will either get the user's record or an HTTP error (it would have been nicer to get back null, I think).

final record = await pb.collection('users').authWithPassword('tom', 'xxx');

I like that I can add more fields to this collection in case I want to associate additional information with that user. In Firebase, one has to create another collection that needs to stay in sync with the auth subsystem.

There is something called an AuthStore in PocketBase that can be asked for the currently signed-in user with pb.authStore.model (the API should decide on whether it deals with items, models or records, I think) and can be observed for changes via onChange which is a regular Stream which is nice. To sign-out, you've supposed to call pb.authStore.clear(). The API then forgets the auth token.

If you configure PocketBase with an SMTP server address that can receive mails, the system also supports email confirmation or password reset. I haven't tried that yet.

Overall, I really like the simplicity of the system.

111 Upvotes

8 comments sorted by

4

u/cashdaddymusk Jan 03 '23

How does it compare to appwrite or supabase?

8

u/eibaan Jan 03 '23

I'm not qualified to answer that.

Supabase is a startup funded with $110 Mio positioning itself as a Firebase competitor. Appwrite was funded with $37 Mio and calls itself a BaaS. PocketBase is an open source project created by Gani Georgiev with no VC or publicly announced world domination plans.

29

u/Radeon546 Jan 02 '23

Man, i need more posts like this. This is what FlutterDev needs. I tried it, and it's good. I want to use it in next project for as imple budget app.

1

u/pverma8172 Sep 17 '23

did you used it?

3

u/ikhazen Jan 02 '23

do you have a repo of your sample app?

I wanna learn more flutter app structures and with different backends.

so far, I've only tried sqlite db for a small app and currently learning clean architecture.

3

u/eibaan Jan 02 '23

Unfortunately I don't have any sample app I can provide, but PocketBase's built-in documentation is quite good and contains automatically generated Dart API examples.

1

u/Own-Cartographer9826 Jan 27 '23

Thank you for this excellent post.