objectbox 0.6.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 88

ObjectBox for Dart/Flutter #

ObjectBox for Dart is a standalone database storing Dart objects locally, with strong ACID semantics.

Flutter/Dart compatibility #

This library depends on a new Dart feature, FFI, introduced in Dart 2.5 (Flutter 1.9) as a feature preview. However, it has changed significantly in Dart 2.6/Flutter 1.12, i.e. introduced breaking changes we had to reflect. Versions starting with ObjectBox 0.5 support Dart 2.6+ as well as Flutter 1.12+.

The last supported version for Flutter 1.9/Dart 2.5 is ObjectBox 0.4.*, so if you can't upgrade yet, please use the latest 0.4.x version instead.

Installation #

Add the following dependencies to your pubspec.yaml:

dependencies:
  objectbox: ^0.6.4

dev_dependencies:
  build_runner: ^1.0.0
  objectbox_generator: ^0.6.4

Proceed based on whether you're developing a Flutter app or a standalone dart program:

  1. Flutter only steps:
    • Install the packages flutter pub get
  2. Dart standalone programs:
    • Install the packages pub get
    • Install objectbox-c system-wide:
      • macOS/Linux: execute the following command (answer Y when it asks about installing to /usr/lib)
           bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/master/install.sh)
        
      • macOS: if dart later complains that it cannot find the libobjectbox.dylib you probably have to unsign the dart binary (source: dart issue):
           sudo codesign --remove-signature $(which dart)
        
      • Windows: use "Git Bash" or similar to execute the following command
           bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/master/install.sh)
        
        Then copy the downloaded lib/objectbox.dll to C:\Windows\System32\ (requires admin privileges).

ObjectBox generates code binding code for classes you want stored based using build_runner. After you've defined your persisted entities (see below), run pub run build_runner build or flutter pub run build_runner build.

Getting started #

In general, Dart class annotations are used to mark classes as ObjectBox entities and provide meta information. Entity IDs and UIDs that are defined in their respective annotations need to be unique across all entities, while property IDs only need to be unique in their respective entity; property UIDs also need to be globally unique.

Each entity is required to have an ID property of type int. Already persisted entities have an ID greater or equal to 1. New (not yet persisted) objects typically have ID value of 0 or null: calling Box.put automatically assigns a new ID to the object.

Example #

For a code example, see example/README.md

Box #

Box is your main interface for storing and retrieving data.

var box = Box<Note>(store);
    
var note = Note(text: "Hello");
note.id = box.put(note);
print("new note got id ${note.id}");
print("refetched note: ${box.get(note.id)}");

Query and QueryBuilder #

Basic querying can be done with e.g.:

// var store ...
// var box ...

box.putMany([Note(), Note(), Note()]);
box.put(Note.construct("Hello world!"));

final queryNullText = box.query(Note_.text.isNull()).build();

assert(queryNullText.count() == 3);

queryNullText.close(); // We have to manually close queries and query builders.

More complex queries can be constructed using and/or operators. Also there is basic operator overloading support for greater, less, and and or, respectively >, <, &, |.

// final box ...

box.query(value.greaterThan(10).or(date.isNull())).build();

// equivalent to

final overloaded = (value > 10) | date.isNull();
box.query(overloaded as Condition).build(); // the cast is necessary due to the type analyzer

Ordering #

The results from a query can be ordered using the order method, e.g.

final q = box.query(Entity_.number > 0)
  .order(Type_.number)
  .build();

// ...

final qt = box.query(Entity_.text.notNull())
  .order(Entity_.text, flags: Order.descending | Order.caseSensitive)
  .build();

Help wanted #

ObjectBox for Dart is still in an early stage with limited feature set (compared to other languages). To bring all these features to Dart, we're asking the community to help out. PRs are more than welcome! The ObjectBox team will try its best to guide you and answer questions.

Feedback #

Also, please let us know your feedback by opening an issue: for example, if you experience errors or if you have ideas for how to improve the API. Thanks!

FAQ #

Q: After adding ObjectBox, the size of the APK increased significantly. Why is that?
A: Flutter compresses its native libraries (.so files) by default in the APK. ObjectBox instructs the Android build to use uncompressed native libraries instead (following the official Android recommendations). This setting affects the Flutter native libraries as well. Thus the now uncompressed Flutter libraries add to the APK size as well; we've seen an additional 19 MB for the standard Flutter libraries. This is bad, right? Nope, actually uncompressed libraries use less storage space on device and have other advantages. For details, please review the official Android recommendations and the ObjectBox FAQ entry on this. Both links also explain how to force compression using android:extractNativeLibs="true".

See also #

License #

Copyright 2020 ObjectBox Ltd. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

0.6.4 (2020-05-12) #

  • Update to objectbox-swift 1.3.0
  • Update to objectbox-android 2.5.1

0.6.3 (2020-05-07) #

  • Update FlatBuffers to 1.12.0
  • Provide error hinting when DB can't be created (e.g. when an app docs directory isn't passed properly on Flutter).

0.6.2 (2020-03-09) #

  • Support large object arrays on 32-bit platforms/emulators.

0.6.1 (2020-01-23) #

  • Fix Flutter Android/iOS release build failures
  • Updated to objectbox-c 0.8.2

0.6.0 (2019-12-19) #

  • Flutter iOS support
  • Generator fixes and rework to support multiple entity files in addition to many entities in a single file. Please move objectbox-model.json to lib/ before running the generator.
  • Simplified Android support (automatic dependency).
  • Docs improvements
  • Updated to objectbox-c 0.8.1

0.5.0 (2019-11-18) #

  • Dart 2.6 support - breaking change due to Dart 2.6 FFI changes. Please keep using 0.4 if you're on Dart 2.5/Flutter 1.9. (thanks Jasm Sison for #57)
  • Docs fixes & improvements

0.4.0 (2019-10-31) #

  • Flutter Android support
  • Queries for all currently supported types
    (thanks Jasm Sison for #27 and #46)
  • More Box functions (count, isEmpty, contains, remove and their bulk variants) (thanks liquidiert for #42 and #45)
  • Explicit write transactions (thanks liquidiert for #50)
  • Resolved linter issues (thanks Gregory Sech for #31)
  • Updated to objectbox-c 0.7.2
  • First release on pub.dev

0.3.0 (2019-10-15) #

  • ID/UID generation and model persistence (objectbox-model.json)
  • CI tests using GitHub Actions
  • Code cleanup, refactoring and formatting (thanks Jasm Sison for #20 & #21)

0.2.0 (2019-09-11) #

  • UTF-8 support for Store and Box (thanks Jasm Sison for #14!)
  • Bulk put and get functions (getMany, getAll, putMany)
  • Updated to objectbox-c 0.7
  • Basic Store options
  • Minimal unit tests
  • Removed reflection code, switched to model code generation instead
  • Minimal Flutter Desktop example for Dart 2.5.0

0.1.0 (2019-09-03) #

  • Minimal Store setup
  • Minimal Box with put and get

example/README.md

ObjectBox Examples #

In the following file, e.g. models.dart, we import objectbox.dart to get definitions for @Entity, @Id and other annotations and define a single entity that should be persisted by ObjectBox. You could have multiple entities in the same file or you can have them spread across multiple files in the lib directory tree.

import "package:objectbox/objectbox.dart";

@Entity()
class Note {
    @Id()       // required; stored as a 64-bit unsigned integer in ObjectBox
    int id;
    String text;
    
    Note({this.text}); // empty default constructor needed but it can have optional args
    toString() => "Note{id: $id, text: $text}";
}

ObjectBox generator will look for all @Entity annotations in your lib folder and create a single database definition lib/objectbox-model.json and supporting code in lib/objectbox.g.dart. You should commit objectbox-model.json into your source control (e.g. git) and add objectbox.g.dart to the ignore list (e.g. .gitignore), otherwise the build_runner will complain about it being changed each time you pull a change.

Note: the generator will process lib and test folders separately and create a separate database in each one, if it finds annotations there. This is useful if you need a separate test DB, but if you're just writing tests for your own code you won't have any annotations in the test folder so no DB will be created there.


To use ObjectBox and store the just defined entity, you should import objectbox.g.dart and create the Store. Finally, you will create a Box<Note> which gives you a typed interface for storing and retrieving Note objects.

import 'objectbox.g.dart'; // this file will be generated by ObjectBox after running `pub run build_runner build`

void main() {
  var store = Store(getObjectBoxModel()); // Note: getObjectBoxModel() is generated for you in objectbox.g.dart
  var box = Box<Note>(store);
  
  var note = Note(text: "Hello");
  note.id = box.put(note);
  print("new note got id ${note.id}");
  print("refetched note: ${box.get(note.id)}");
  
  store.close();
}

Flutter #

As opposed to a plain Dart app which runs directly on your PC, there are more restrictions where your Flutter app can write data. Therefore, you should give ObjectBox a full path to a per-app documents directory, where to store the data even when a user closes your app.

If you didn't specify this path to ObjectBox, it would try to use a default "objectbox" directory where the app is currently running, but it doesn't have permissions to write there: failed to create store: 10199 Dir does not exist: objectbox (30).

To configure ObjectBox properly, you can use getApplicationDocumentsDirectory() from the path_provider package. See Flutter: read & write files for more info. Have a look how it's done in the Flutter example app:

import 'package:path_provider/path_provider.dart';

class _MyHomePageState extends State<MyHomePage> {
  Store _store;

  @override
  void initState() {
    super.initState();
    
    getApplicationDocumentsDirectory().then((dir) {
      _store = Store(getObjectBoxModel(), directory: dir.path + "/objectbox");
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  objectbox: ^0.6.4

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:objectbox/objectbox.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
77
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
88
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.15
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform Android

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package does not support Flutter platform Linux

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package does not support Flutter platform Web

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package does not support Flutter platform Windows

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package does not support Flutter platform iOS

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package does not support Flutter platform macOS

Because:

  • package:objectbox/objectbox.dart that declares support for platforms:

Package not compatible with runtime js

Because:

  • package:objectbox/objectbox.dart that imports:
  • package:objectbox/src/query/query.dart that imports:
  • package:objectbox/src/bindings/signatures.dart that imports:
  • package:ffi/ffi.dart that imports:
  • package:ffi/src/allocation.dart that imports:
  • dart:io

Health suggestions

Fix lib/src/box.dart. (-0.50 points)

Analysis of lib/src/box.dart reported 1 hint:

line 4 col 8: Unused import: 'common.dart'.

Format lib/integration_test.dart.

Run flutter format to format lib/integration_test.dart.

Format lib/src/bindings/bindings.dart.

Run flutter format to format lib/src/bindings/bindings.dart.

Fix additional 15 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/bindings/data_visitor.dart (Run flutter format to format lib/src/bindings/data_visitor.dart.)
  • lib/src/bindings/flatbuffers.dart (Run flutter format to format lib/src/bindings/flatbuffers.dart.)
  • lib/src/bindings/helpers.dart (Run flutter format to format lib/src/bindings/helpers.dart.)
  • lib/src/bindings/signatures.dart (Run flutter format to format lib/src/bindings/signatures.dart.)
  • lib/src/bindings/structs.dart (Run flutter format to format lib/src/bindings/structs.dart.)
  • lib/src/common.dart (Run flutter format to format lib/src/common.dart.)
  • lib/src/model.dart (Run flutter format to format lib/src/model.dart.)
  • lib/src/modelinfo/iduid.dart (Run flutter format to format lib/src/modelinfo/iduid.dart.)
  • lib/src/modelinfo/modelentity.dart (Run flutter format to format lib/src/modelinfo/modelentity.dart.)
  • lib/src/modelinfo/modelinfo.dart (Run flutter format to format lib/src/modelinfo/modelinfo.dart.)
  • lib/src/modelinfo/modelproperty.dart (Run flutter format to format lib/src/modelinfo/modelproperty.dart.)
  • lib/src/query/builder.dart (Run flutter format to format lib/src/query/builder.dart.)
  • lib/src/query/query.dart (Run flutter format to format lib/src/query/query.dart.)
  • lib/src/store.dart (Run flutter format to format lib/src/store.dart.)
  • lib/src/util.dart (Run flutter format to format lib/src/util.dart.)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
ffi ^0.1.3 0.1.3
flat_buffers 1.12.0 1.12.0
Dev dependencies
build_runner ^1.0.0
objectbox_generator
pedantic ^1.8.0+1
test ^1.0.0