Flutter MongoDB数据库连接插件appstitch_mongodb的使用

Flutter MongoDB数据库连接插件appstitch_mongodb的使用

平台

  • iOS
  • Android
  • Web

使用

创建一个文档
void insertUser() async {
    final user = User(
        email: "steve@theavengers.com",
        firstName: "Steve",
        lastName: "Rogers",
        dateOfBirth: DateTime(1918, 07, 04)).toJson();

    final result = await db
        .collection("users")
        .insert(user);

    if (result.success!) {
        final userID = result.id!;
    } else {
        print(result.message!);
    }
}
获取一个文档
void fetchUser() async {

    final result = await db
        .collection("logging")
        .id(userID)
        .include(
            ["email", "firstName",
        "dateOfBirth"])
        .fetch();

    if (result.success!) {

        user = User.fromJson(result.doc!);
    } else {
      print(result.message!);
    }
}
获取多个文档
void fetchUsers() async {
    startSpinner();

    final result = await db
        .collection("logging")
        .where("email", OperatorType.equal, "s.rogers@theavengers.com")
        .limit(20)
        .fetch();

    if (result.success!) {
        final users = result.docs!
    } else {
      print(result.message!);
    }
  }

读取选项

选项 类型 描述
collection String 必需。集合名称
id String 返回特定文档。返回1个文档或null
where string, OperatorType, object 查询对象,用于过滤文档
include String[] 返回特定文档字段。默认情况下,_id 字段包含在输出文档中
exclude String[] 防止特定文档字段被返回。默认情况下,_id 字段不被排除
limit number 限制返回文档的数量。默认返回50个文档
startAfter number 跳过前n个文档,其中n是指定的跳过数量,然后传递剩余的文档

更新一个文档
void updateUser() async {
    user.email = "test@google.com";

    final result =
        await db.collection("logging").id(userID).update(user.toJson());

    if (result.success!) {
      print("Successfully Updated");
    } else {
      print(result.message!);
    }
  }
删除一个文档
void deleteUser() async {

    final result = await db
    .collection("logging")
    .id(userID).delete();

    if (result.success!) {
        print("Successfully Deleted");
    } else {
      print(result.message!);
    }
  }

写入选项

选项 类型 描述
collection String 必需。集合名称
id String 返回特定文档。返回1个文档或null
where string, OperatorType, object 查询对象,用于过滤文档

Algolia集成

Algolia 集成可以保持您的 MongoDB 和 Algolia 数据同步。syncData 选项在所有写操作(插入、更新、删除)上可用。

final result = await db
    .collection("users")
    .insert(_user, WriteOptions(syncData: true))

安装

dependencies:
  appstitch_core:   ^1.0.4
  appstitch_mongodb: ^1.0.0

初始化

import 'package:appstitch_core/options.dart';
import 'package:appstitch_core/core.dart';
import 'package:appstitch_mongodb/mongodb.dart';

Core core = Core();
MongoDB db = MongoDB();

[@override](/user/override)
void initState() {
  super.initState();

  final options = Options(appstitchKey, clientID: clientID);
  core.initialize(options);
}

示例代码

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](/user/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](/user/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](/user/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](/user/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: [
            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(),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter MongoDB数据库连接插件appstitch_mongodb的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter MongoDB数据库连接插件appstitch_mongodb的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


appstitch_mongodb 是一个用于在 Flutter 应用中连接和操作 MongoDB 数据库的插件。它允许你直接从 Flutter 应用中与 MongoDB 数据库进行交互,而无需设置后端服务器。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 appstitch_mongodb 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  appstitch_mongodb: ^0.0.1  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在你的 Dart 文件中导入插件并初始化它:

import 'package:appstitch_mongodb/appstitch_mongodb.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final MongoClient mongoClient = MongoClient(
    appId: 'your-appstitch-app-id',  // 你的 AppStitch App ID
    apiKey: 'your-api-key',         // 你的 API Key
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MongoDB in Flutter'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              await connectToDatabase();
            },
            child: Text('Connect to MongoDB'),
          ),
        ),
      ),
    );
  }

  Future<void> connectToDatabase() async {
    try {
      await mongoClient.connect();
      print('Connected to MongoDB!');
    } catch (e) {
      print('Failed to connect to MongoDB: $e');
    }
  }
}

3. 执行数据库操作

一旦连接成功,你可以使用 mongoClient 对象来执行各种数据库操作,如插入、查询、更新和删除数据。

插入数据

Future<void> insertData() async {
  try {
    await mongoClient.insert('your-database-name', 'your-collection-name', {
      'name': 'John Doe',
      'age': 30,
      'email': 'john.doe@example.com',
    });
    print('Data inserted successfully!');
  } catch (e) {
    print('Failed to insert data: $e');
  }
}

查询数据

Future<void> queryData() async {
  try {
    var result = await mongoClient.find('your-database-name', 'your-collection-name', {});
    print('Query result: $result');
  } catch (e) {
    print('Failed to query data: $e');
  }
}

更新数据

Future<void> updateData() async {
  try {
    await mongoClient.update('your-database-name', 'your-collection-name', {
      'name': 'John Doe'
    }, {
      '\$set': {'age': 31}
    });
    print('Data updated successfully!');
  } catch (e) {
    print('Failed to update data: $e');
  }
}

删除数据

Future<void> deleteData() async {
  try {
    await mongoClient.delete('your-database-name', 'your-collection-name', {
      'name': 'John Doe'
    });
    print('Data deleted successfully!');
  } catch (e) {
    print('Failed to delete data: $e');
  }
}

4. 断开连接

当你不再需要连接时,记得断开连接以释放资源:

Future<void> disconnectFromDatabase() async {
  try {
    await mongoClient.disconnect();
    print('Disconnected from MongoDB!');
  } catch (e) {
    print('Failed to disconnect from MongoDB: $e');
  }
}
回到顶部