This is a guest post written by Luca Christille. Luca is a self-taught developer, and the creator of Fluttercouch. He wrote his first line of code when he was eight years old, and his passion for development has only grown since. He is a Google certified Android developer, and works full-time as a full stack engineer. He spends much of his down time freelancing as a mobile developer.
Luca is no stranger to NoSQL databases, having spent time working with and evaluating various solutions. Ultimately, he was drawn to Couchbase for its data synchronization capabilities as a major requirement for many mobile apps is to have “offline-first” functionality.
Early on, Luca focused strictly on creating fully native apps. However, he eventually encountered a client that required a cross-platform solution, and after researching the multitude of options available he chose to use Flutter.
Flutter: Design Beautiful Apps
Taking a step back, you may be asking yourself, what is Flutter? Simply put, Flutter is an open source SDK for creating high-performance, high-fidelity mobile apps for iOS and Android. The Flutter framework makes it easy for you to build user interfaces that react smoothly in your app, while reducing the amount of code required to synchronize and update your app’s view.
Like many other development ecosystems Flutter provides the ability to integrate with componentized code projects known as Flutter packages. Flutter packages help developers integrate complex functionality into their mobile applications. Packages can be anything from Dart-based libraries that extend the standard Flutter framework capabilities to solutions that interact directly with the native layers and enable new functionalities based upon SDKs from Android and iOS.
Introducing Fluttercouch
Fluttercouch is a package that seamlessly integrates Couchbase Mobile functionality into your Flutter apps, managing your Android and iOS native layers. The package prevents you from having to create boilerplate code to set up the database, use documents and run replication. Ultimately, Fluttercouch allows you to focus on creating your application logic, using Dart, instead of building platform specific code with the native Couchbase Mobile SDKs.
Getting Started
To get started using Fluttercouch you’ll need to add a dependency directive to the pubspec.yaml file.
1 2 |
dependencies: fluttercouch: ^0.5.0 |
After adding the dependency directive you can use Fluttercouch in any model class you already have, or just start with a new one. You can extend model classes of InheritedWidget, Scoped Model or Bloc. Once extended, the Fluttercouch superpowers are unlocked!
1 2 3 4 5 6 7 |
class CounterBlock extends Bloc<CounterBlock, int> with Fluttercouch { class FrogColor extends InheritedWidget with Fluttercouch { class CounterModel extends Model with Fluttercouch { class MyModel extends Object with Fluttercouch { |
Basic Operations
From this point on you can fetch an instance of an earlier created database or instantiate a new one directly from your class. Once a database is initialized it becomes the default choice, and any further method invocation will refer to it. After creating a database instance you’ll have the ability to easily perform all of the CRUD operations you’ve come to expect with Couchbase Lite databases.
For example, you can retrieve a document by its id and get a string from the property myProperty
. Then convert the document to a Mutable Document, modify it and re-save it back.
1 2 3 4 5 6 7 |
helloCouchbase() async { await initDatabaseWithName('myDatabase'); Document myDocument = await getDocumentWithId('hello::world'); String helloWorld = myDocument.getString('greetings'); MutableDocument myMutableDocument = myDocument.toMutable(); myMutableDocument.setString('helloKey', 'worldValue'); saveDocument(myMutableDocument); |
Working with Replicators
Data replication is also possible with Fluttercouch. Using Dart, you can easily create and configure replicators.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Supplies the address of the database replicated by the Sync Gateway server. // In case you want to enable SSL encryption, use wss:// insted of ws://. // To connect to a local Sync Gateway instance, use localhost as hostname for iOs simulator, and 10.0.2.2 for Android simulator. setReplicatorEndpoint("ws://your-server-address:4984/yourReplicationDatabaseName"); // Sets the replication type as PULL, PUSH or PUSH_AND_PULL setReplicatorType("PUSH_AND_PULL"); // Sets the replication as continuous setReplicatorContinuous(true); // Sets a BasicAuthenticator for the replication. The methods accept a parameter of type Map<String, String> // with two keys named "username" and "password". setReplicatorBasicAuthentication(<String, String>{ "username": "yourUsername", "password": "yourPassword" }); // Sets a SessionAuthenticator for the replication. SessionID is retrieved querying the public REST API of your Sync Gateway setReplicatorSessionAuthentication(sessionID); // Before starting the replication, you must init the replicator object initReplicator(); // Starts the replication startReplicator(); // Stops the replication stopReplicator(); |
You can also listen for replication events by passing a function to the listenReplicatorEvents method. The listenReplicatorEvents calls the function with a parameter containing the event type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
listenReplicationEvents((dynamic event) { switch(event) { case ("BUSY"): // executed when the replicator status changes to BUSY case ("IDLE"): // executed when the replicator status changes to IDLE case ("OFFLINE"): // executed when the replicator status changes to OFFLINE case ("STOPPED"): // executed when the replicator status changes to STOPPED case ("CONNECTING"): // executed when the replicator status changes to CONNECTING } } ); |
Next Steps
You are now ready to unleash the potential of Couchbase in your next Flutter application! Download Fluttercouch from the pub repository, and more detailed documentation, you can visit the project page on GitHub for a complete reference on how to interact with your database.
Fluttercouch is an open-source project that I currently maintain and add to during my free time. In the near future I’m looking forward to completing the N1QL Query abstraction layer for Dart, adding support for Blob and Sub-Document operations, and many other features that exist within the CouchbaseMobile SDKs. The project would benefit greatly from community contributions, and any comments, issues and/or pull-requests would be appreciated!
Hi this is client-side database or server-side database?
This is for Couchbase Lite embedded database (not Couchbase Server)
How would this sync with an ever-changing, live (CRUD) Couchbase Server DB?
For example, let’s say you have 1 million documents on your CB server, which steadily change – some get deleted, some get updated, new ones get created, … and all that possibly several times every minute or even second – but obviously you wouldn’t want to sync the whole server DB with the client all the time, instead only the relevant documents (let’s say, 10 at a time)… is that doable? Or would that rather require to have a direct connection to the server DB from the client, and how would that work via Dart?