appstitch_mongodb 1.0.0-prerelease
appstitch_mongodb: ^1.0.0-prerelease copied to clipboard
Appstitch client for MongoDB CRUD operations.
example/lib/main.dart
import 'package:appstitch_core/options.dart';
import 'package:appstitch_core/core.dart';
import 'package:appstitch_mongodb/mongodb.dart';
import 'package:appstitch_mongodb/types.dart';
import 'package:flutter/material.dart';
import '../types/user.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Apstitch MongoDB example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Appstitch MongoDB example'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
/// TODO
// Appstitch
bool loading = false;
final String appstitchKey = "";
final String clientID = "";
Core core = Core();
int userCount = 0;
String userID = "";
User user = User();
List<User> users = List.empty();
MongoDB db = MongoDB();
@override
void initState() {
super.initState();
final options = Options(appStitchKey: appstitchKey, clientID: clientID);
core.initialize(options);
}
void showMessage(String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 1),
));
}
void startSpinner() {
setState(() {
loading = true;
});
}
void stopSpinner() {
setState(() {
loading = false;
});
}
void insertUser() async {
startSpinner();
final _user = User(
email: "test@example.com",
firstName: "test",
lastName: "example",
dateOfBirth: DateTime(1991, 06, 25));
// Example using then/catch
db
.collection("logging")
.insert(_user.toJson(), WriteOptions(syncData: true))
.then((result) {
if (result.success!) {
setState(() {
userID = result.id!;
});
showMessage("User Created");
} else {
showMessage(result.message!);
}
stopSpinner();
}).catchError((onError) {
showMessage("Unable to create user");
stopSpinner();
});
}
void fetchUser() async {
startSpinner();
final result = await db
.collection("logging")
.id(userID)
.include(["email", "firstName", "dateOfBirth"]).fetch();
if (result.success!) {
setState(() {
user = User.fromJson(result.doc!);
});
showMessage("Fetched User");
} else {
showMessage(result.message!);
}
stopSpinner();
}
void fetchAllUsers() async {
startSpinner();
final result = await db
.collection("logging")
.where("email", OperatorType.equal, "test@example.com")
.limit(20)
.fetch();
if (result.success!) {
setState(() {
userCount = result.docs!.length;
});
showMessage("${result.docs!.length} fetched");
} else {
showMessage(result.message!);
}
stopSpinner();
}
void updateUser() async {
startSpinner();
user.email = "test@google.com";
final result =
await db.collection("logging").id(userID).update(user.toJson());
if (result.success!) {
showMessage("Successfully Updated");
} else {
showMessage(result.message!);
}
stopSpinner();
}
void deleteUser() async {
startSpinner();
final result = await db.collection("logging").id(userID).delete();
if (result.success!) {
setState(() {
user = User();
});
showMessage("Successfully Deleted");
} else {
showMessage(result.message!);
}
stopSpinner();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Total Users : $userCount',
style: Theme.of(context).textTheme.bodyText1,
),
Text(
'User ID:$userID',
style: Theme.of(context).textTheme.bodyText1,
),
Text(
'First Name:${user.firstName ?? ""}',
style: Theme.of(context).textTheme.bodyText1,
),
Text(
'Last Name: ${user.lastName ?? ""}',
style: Theme.of(context).textTheme.bodyText1,
),
Text(
'Email: ${user.email ?? ""}',
style: Theme.of(context).textTheme.bodyText1,
),
ElevatedButton(
child: Text("Create User"),
onPressed: insertUser,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0),
child: ElevatedButton(
child: Text("Fetch User"),
onPressed: fetchUser,
)),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0),
child: ElevatedButton(
child: Text("Fetch All Users"),
onPressed: fetchAllUsers,
)),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0),
child: ElevatedButton(
child: Text("Update Email"),
onPressed: updateUser,
)),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0),
child: ElevatedButton(
child: Text("Delete User"),
onPressed: deleteUser,
)),
Visibility(
visible: loading,
child: CircularProgressIndicator(),
),
],
),
),
);
}
}