flutter_mongo_stitch 0.8.1+1 copy "flutter_mongo_stitch: ^0.8.1+1" to clipboard
flutter_mongo_stitch: ^0.8.1+1 copied to clipboard

discontinuedreplaced by: flutter_mongodb_realm

A Flutter plugin for using services of the serverless platform MongoDB Stitch.

flutter_mongo_stitch #

Unofficial Flutter plugin for using MongoDB Stitch services on Android, iOS and web.

Getting started #

For using it on your app:

import 'package:flutter_mongo_stitch/flutter_mongo_stitch.dart';
copied to clipboard

For API reference check here

The minimum required it's Android 5.0(API 21) or iOS 11.0

Setup #

Doesn't require any setup besides adding as a dependency Web integration automatically!

Supported Features #

Database support:

  • Insert
  • Find
  • Delete
  • Update
  • Watch (also to specified IDs or with Filter)
  • Aggregate [X]

Auth Providers:

  • Email/Password
  • Anonymously
  • Google [X]
  • Facebook [X]

Authentication

  • Auth Listener
  • Reset Password
  • Login/Sign in/Logout

Functions

  • Calling a Stitch function

Note: Other more features will come in the future :)

Note: [X] = Not implemented on Web

Usage #

Initialization #

Inorder to connect a StitchApp to flutter add your main function:

main() async{
  // ADD THESE 2 LINES
  WidgetsFlutterBinding.ensureInitialized();
  await MongoStitchClient.initializeApp(<your_app_id>);
  
  // other configurations..
  
  runApp(MyApp());
}
copied to clipboard

Inorder to use the client define:

  final client = MongoStitchClient();
copied to clipboard

Authentication #

Inorder to use the auth part define:

final auth = client.auth;
copied to clipboard

You can retrieve the current logged user by:

final user = client.auth.user;

// for more details (like email,birthday) use his 'profile' attribute
// For example:
final userEmail = user.profile.email;
copied to clipboard

Login

Login a user with Anonymous provider:

CoreStitchUser mongoUser = await auth.loginWithCredential(AnonymousCredential());
copied to clipboard

Login a user with Email\Password provider:

CoreStitchUser mongoUser = await auth.loginWithCredential(
  UserPasswordCredential(username: <email_address>, password: <password>));
copied to clipboard

For login with Facebook import the required flutter's package and configure in the native side as their instructions.

Login a user using Google provider:

Inorder to make Google login works, please follow the follwing instructions use the following:

1. Remove (if used) the version used from pubspec.yaml (ex. google_sign_in: ^4.5.1)
2. Use git repo version instead (copy from below)
3. In dart code use also serverClientId parmeter

This has to be done in order to get the auth code need by the Mongo Stitch SDK

calling on flutter:

CoreStitchUser mongoUser = await auth.loginWithCredential(
  GoogleCredential(
    serverClientId: <Google Server Client Id>, // just the start from "<ID>.apps.googleusercontent.com"   
    scopes: <list of scopes>,
));
copied to clipboard

in pubspec.yaml:

.. (other dependencies)
google_sign_in:
  git:
    url: git://github.com/fbcouch/plugins.git
    path: packages/google_sign_in
    ref: server-auth-code
copied to clipboard
CoreStitchUser mongoUser = await auth.loginWithCredential(
  GoogleCredential(
    serverClientId: <Google Server Client Id>, // just the start from "<ID>.apps.googleusercontent.com"   
    scopes: <list of scopes>,
));
copied to clipboard

Login a user using Facebook provider:

CoreStitchUser mongoUser = await auth.loginWithCredential(
  FacebookCredential(<access_token>));
copied to clipboard

NOTE: In any case , if mongoUser != null the login was successful.

Register

// Login a user with Email\Password
CoreStitchUser mongoUser = await auth.registerWithEmail(
    email: <email_address>, password: <password>);
copied to clipboard

Logout

// Logout the current user:
await auth.logout()
copied to clipboard

Reset Password

You can send an email to reset user password: (email must be linked to an existing account)

await client.auth.sendResetPasswordEmail(<YOUR_DESIRED_EMAIL>);
copied to clipboard

Auth Listener

You can be notified when the auth state changes, such as login/logout..

/// for using as smart navigation according to user logged in or not
StreamBuilder _authBuilder(BuildContext context) {
  return StreamBuilder(
    stream: client.auth.authListener(),
    builder: (context, AsyncSnapshot snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:case ConnectionState.waiting:
          // show loading indicator
          return Scaffold(body: Center(child: CircularProgressIndicator()));
        case ConnectionState.active:
          // log error to console
          if (snapshot.error != null) {
            return Container(
              alignment: Alignment.center,
              child: Text(snapshot.error.toString()),
            );
          }

          // redirect to the proper page
          return snapshot.hasData ? HomeScreen() : LoginScreen();

          default:
            return LoginScreen();
        }
      },
  );
}
copied to clipboard

Database #

To get access to a collection:

  final collection = client.getDatabase(<database_name>).getCollection(<collection_name>);
copied to clipboard

Insert


collection.insertOne(MongoDocument({
  // key-value pairs describing the document
}));

// OR

List<MongoDocument> documents = ...;
collection.insertMany(documents);
copied to clipboard

Find

filtering can be used with QuerySelector class for more robust code


// fetch all document in the collection
var docs = collection.find();

// fetch all document in the collection applying some filter
var docs = collection.find(
  filter: {
    "year": QuerySelector.gt(2010)..lte(2014), // == 'year'>2010 && 'year'<=2014
});

// optional: can also add find options (projection/limit/sort)
var docs = await collection.find(
  filter: {
    "year": QueryOperator.gt(2010)..lte(2014),
  },
  options: RemoteFindOptions(
    projection: {
      "title": ProjectionValue.INCLUDE,
      "rated": ProjectionValue.INCLUDE,
      "year": ProjectionValue.INCLUDE,
    },
    limit: 70,
    sort: {
      "year": OrderValue.ASCENDING,
    }
  ),
);


// the same as above, but just get the first matched one
var document = await collection.findOne();

var document = await collection.findOne(
  filter: {
    "year": QuerySelector.gt(2010)..lte(2014), // == 'year'>2010 && 'year'<=2014
});


// fetch the number of document in the collection
int collectionSize = await collection.count();

// count the number of document that apply to some filter
int size = await collection.count({
    "age": 25,
});
copied to clipboard

Delete

filtering can be used with QuerySelector class for more robust code

// fetch all documents in the collection
var deletedDocs = await collection.deleteMany({});

// fetch the first document in the collection applying some filter
var deletedDocs = await collection.deleteOne({"age": 24});

// fetch all document in the collection applying some filter
var deletedDocs = 
  await collection.deleteMany({"age": QuerySelector.gte(24)});
copied to clipboard

Update


await collection.updateMany(
  // adding a filter (optional)
  filter:{
    "name": "adam",
  },

  // adding an update operation (as matched the MongoDB SDK ones)
  update: UpdateSelector.set({
    "quantity": 670,
  })
);

// OR
await collection.updateOne(
  // the same as above, just it's updated the only first matched one
)
copied to clipboard

Watch

First, Get the stream to subscribed to any document change in the collection

final stream = collection.watch();

// (optional) can watch only specified documents by their ids:
// 1. if they defined as ObjectId type
final stream2 = myCollection.watch(ids: ["5eca2d9fff448a4cbf8f6627"]);

// 2. if they defined as String type (`asObjectIds` is true by default)
final stream3 = myCollection.watch(ids: ["22", "8"], asObjectIds: false);
copied to clipboard

OR get the stream to subscribed to a part of the collection applying filter on the listened documents

final streamFilter = collection.watchWithFilter({
  "age": QuerySelector.lte(26)
});
copied to clipboard

Afterwards, set a listener to a change in the collection

stream.listen((data) {
  // data contains JSON string of the document that was changed
  var fullDocument = MongoDocument.parse(data);
  
  // Do other stuff...
});
copied to clipboard

Aggregation

define Pipeline Stages for aggregation, i.e:

List<PipelineStage> pipeline = [
  PipelineStage.addFields({
    "totalHomework": AggregateOperator.sum("homework"),
    "totalQuiz": AggregateOperator.sum("quiz"),
  }),
  PipelineStage.addFields({
    "totalScore": AggregateOperator.add(
        ["totalHomework", "totalQuiz", "extraCredit"]),
  }),
];
copied to clipboard

And then set the pipelines stages to the aggregate function:

 var list = await collection.aggregate(pipeline);
copied to clipboard

Another usages (not all stages are supported):

List<PipelineStage> pipeline = [
  PipelineStage.skip(2),
  PipelineStage.match({"status": "A"}),
  PipelineStage.group(
    "cust_id",
    accumulators: {"total": AggregateOperator.sum("amount")},
  ),
];

List<PipelineStage> pipeline = [
  PipelineStage.sample(2),
];

// can also RAW typed one
List<PipelineStage> pipeline = [

  PipelineStage.raw({
        //... some expression according to the MongoDB API
  }),
  PipelineStage.raw({
        //... some expression according to the MongoDB API
  }),
  ...
];
copied to clipboard

Functions #

for calling a defined stitch function "sum" with argument 3&4

var result = await client.callFunction("sum", args: [3, 4])
copied to clipboard

You can also add a timeout (in ms), i.e 60 seconds:

var result = await client.callFunction("sum", args: [3, 4], requestTimeout: 60000)
copied to clipboard

Donate #

If you found this project helpful or you learned something from the source code and want to thank me, consider buying me a cup of ☕

Note: flutter_mongo_stitch is not directly and/or indirectly associated/affiliated with MongoDBTM , Flutter or Google LLC. #

15
likes
30
points
30
downloads

Publisher

unverified uploader

Weekly Downloads

2024.10.04 - 2025.04.18

A Flutter plugin for using services of the serverless platform MongoDB Stitch.

License

Apache-2.0 (license)

Dependencies

bson, extension, flutter, flutter_mongo_stitch_platform_interface, flutter_mongo_stitch_web, meta, streams_channel, universal_html

More

Packages that depend on flutter_mongo_stitch