couchbase_lite 2.5.1+8

couchbase_lite plugin #

Build Status Coverage Status pub package

A Flutter plugin for Couchbase Lite Community Edition. An embedded lightweight, noSQL database with live synchronization and offline support on Android and iOS.

The goal of this project is to align this library with the Swift SDK API for Couchbase Lite.

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

This project forked from Fluttercouch

Getting Started #

In your flutter project add the dependency:

dependencies:
  couchbase_lite: ^2.5.1
  
  flutter:
      sdk: flutter

For help getting started with Flutter, view the online documentation

Supported Versions #

iOS #

PlatformMinimum OS version
iOS9.0

Android #

PlatformRuntime architecturesMinimum API Level
Androidarmeabi-v7a19
Androidarm64-v8a21
Androidx8619

API References #

Swift SDK API References

Java SDK API References

Note: Syntax follows the Swift SDK but these are the SDKs used for the platform code.

Usage example #

Below is an example for the database using the BLoC pattern ( View <-> BLoC <-> Repository <-> Database )

The files can also be found in the plugin example but are not used in the main.dart. The example will be revised in the near future to use the BLoC pattern.

class AppDatabase {
  AppDatabase._internal();

  static final AppDatabase instance = AppDatabase._internal();

  String dbName = "myDatabase";
  List<Future> pendingListeners = List();
  ListenerToken _replicatorListenerToken;
  Database database;
  Replicator replicator;

  Future<bool> login(String username, String password) async {
    try {
      database = await Database.initWithName(dbName);
      // Note wss://10.0.2.2:4984/my-database is for the android simulator on your local machine's couchbase database
      ReplicatorConfiguration config =
          ReplicatorConfiguration(database, "wss://10.0.2.2:4984/my-database");
      config.replicatorType = ReplicatorType.pushAndPull;
      config.continuous = true;

      // Using self signed certificate
      config.pinnedServerCertificate = "assets/cert-android.cer";
      config.authenticator = BasicAuthenticator(username, password);
      replicator = Replicator(config);

      replicator.addChangeListener((ReplicatorChange event) {
        if (event.status.error != null) {
          print("Error: " + event.status.error);
        }

        print(event.status.activity.toString());
      });

      await replicator.start();
      return true;
    } on PlatformException {
      return false;
    }
  }

  Future<void> logout() async {
    await Future.wait(pendingListeners);
    replicator.removeChangeListener(_replicatorListenerToken);
    _replicatorListenerToken =
        replicator.addChangeListener((ReplicatorChange event) async {
      if (event.status.activity == ReplicatorActivityLevel.stopped) {
        await database.close();
        await replicator.dispose();
        _replicatorListenerToken = null;
      }
    });
    await replicator.stop();
  }

  Future<Map<String, dynamic>> createDocument(Map<String, dynamic> map) async {
    var id = "mydocument::${Uuid().v1()}";

    try {
      String documentId = await database.saveDocumentWithId(id, Document(map));
      var newDoc = Map.from(map);
      newDoc["id"] = documentId;
      return newDoc;
    } on PlatformException {
      return null;
    }
  }

  ObservableResponse<ResultSet> getMyDocument(String documentId) {
    final stream = BehaviorSubject<ResultSet>();
    // Execute a query and then post results and all changes to the stream

    final Query query = QueryBuilder.select([
      SelectResult.expression(Meta.id.from("mydocs")).As("id"),
      SelectResult.expression(Expression.property("foo").from("mydocs")),
      SelectResult.expression(Expression.property("bar").from("mydocs")),
    ])
        .from(dbName, as: "mydocs")
        .where(Meta.id.from("mydocs").equalTo(Expression.string(documentId)));

    final processResults = (ResultSet results) {
      if (!stream.isClosed) {
        stream.add(results);
      }
    };

    return _buildObservableQueryResponse(stream, query, processResults);
  }

  ObservableResponse<T> _buildObservableQueryResponse<T>(
      BehaviorSubject<T> subject,
      Query query,
      ResultSetCallback resultsCallback) {
    final futureToken = query.addChangeListener((change) {
      if (change.results != null) {
        resultsCallback(change.results);
      }
    });

    final removeListener = () {
      final newFuture = futureToken.then((token) async {
        if (token != null) {
          await query.removeChangeListener(token);
        }
      });

      pendingListeners.add(newFuture);
      newFuture.whenComplete(() {
        pendingListeners.remove(newFuture);
      });
    };

    try {
      query.execute().then(resultsCallback);
    } on PlatformException {
      removeListener();
      rethrow;
    }

    return ObservableResponse<T>(subject.debounce(Duration(seconds: 1)), () {
      removeListener();
      subject.close();
    });
  }
}
class ObservableResponse<T> {
  ObservableResponse(this.result, this.onDispose);

  final Observable<T> result;
  final VoidFunc onDispose;

  void dispose() {
    if (onDispose != null) {
      // Do operations here like closing streams and removing listeners
      onDispose();
    }
  }
}

2.5.0 #

  • Initial Release for the plugin using Couchbase Mobile 2.5

2.5.1 #

  • Updated documentation

2.5.1+1 #

  • Changed return type of class Database documentWithId from Map to Document
  • Populated doc/api using dartdoc
  • Fixed some format issues

2.5.1+2 #

  • Added all classes as part of couchbase_lite library to eliminate the need to import every class individually

2.5.1+3 #

  • Fixed issue with Replication EventChannel
  • Added Travis CI and Code Coverage with Coveralls
  • Added support for the having clause
  • Fixed some issues with Queries

2.5.1+4 #

  • Updated documentation
  • Added more test cases

2.5.1+5 #

  • Fixed Replicator Configuration bug which required certain variables like Pinned Certificate to not receive an Platform Error
  • Changed the Map object in Document from unmodifiable to a modifiable copy of the Map object
  • Renamed the functions In,Is,As to in,iS,aS to comply with flutter plugin standards
  • Added a destroy method to Replicator for cleaning up variable references and listeners

2.5.1+6 #

  • Fixed an issue where Query Listeners were not being released
  • Fixed an issue where the database reference was not being released on close for Android

2.5.1+7 #

  • Deprecated Database saveDocument methods and replaced with save taking a MutableDocument as an argument
  • Fixed a concurrent modification exception with query listeners

2.5.1+8 #

  • Fixed a bug on Android which results in an error for not posting results on the UI Thread

example/README.md

couchbase_lite_example #

Demonstrates how to use the couchbase_lite plugin.

Getting Started #

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

1. Depend on it

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


dependencies:
  couchbase_lite: ^2.5.1+8

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support 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:couchbase_lite/couchbase_lite.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
74
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]
87
Learn more about scoring.

We analyzed this package on Sep 13, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
uuid ^2.0.2 2.0.2
Transitive dependencies
charcode 1.1.2
collection 1.14.11 1.14.12
convert 2.1.1
crypto 2.1.3
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
pedantic ^1.5.0