Flutter数据库管理插件nesteggdb的使用

Flutter数据库管理插件NestEggDB的使用

NestEggDB 是一个轻量级的基于文件的 NoSQL 数据库插件,专为 Flutter 设计。它使用 Nest(数据库)和 Egg(文档/数据条目)来管理数据。支持事务、查询以及有序的数据存储。

功能特性

  • 使用 Nest(集合)和 Egg(条目)管理数据。
  • 支持原子性事务。
  • 可通过查询过滤和排序数据。
  • 保留数据的顺序。
  • 使用子 Egg 处理分层数据。

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  egg_nest_db: ^0.0.3

运行以下命令以获取依赖项:

flutter pub get

使用示例

以下是一个完整的示例,展示如何使用 NestEggDB 插件进行基本操作。

初始化 Nest 和 Collection

import 'package:egg_nest_db/nest.dart';

void main() async {
  // 初始化一个 Nest
  final nest = Nest(path: './myDatabase'); // 数据库存储路径
  final collection = nest.eggCollection('myCollection'); // 创建或打开集合
}

添加 Egg

// 向集合中添加一个 Egg
collection.addEgg({
  'id': '1',
  'name': 'First Egg',
  'content': 'This is the first egg.'
});

获取 Egg

// 根据 ID 获取 Egg
final egg = collection.getEgg('1');
print('Egg content: ${egg?.data}');

更新 Egg

// 更新 Egg 的内容
collection.updateEgg('1', {'content': 'Updated content for the first egg.'});

删除 Egg

// 删除指定 ID 的 Egg
collection.deleteEgg('1');

执行事务

// 执行事务操作
nest.runTransaction((transaction) {
  transaction.add(collection, {'id': '2', 'name': 'Second Egg', 'content': 'This is the second egg.'});
});

查询数据

// 查询数据,过滤并按 ID 排序
final query = Query(collection)
  .where('name', 'isEqualTo', 'First Egg')
  .orderBy('id');
final results = query.get();

// 输出查询结果
for (var result in results) {
  print(result);
}

获取所有数据及子 Egg

// 获取集合中的所有数据,包括子 Egg
print(collection.getAllData());

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

1 回复

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


nesteggdb 是一个用于 Flutter 的轻量级数据库管理插件,它基于 SQLite 并提供了一种简单的方式来管理本地数据库。以下是如何在 Flutter 项目中使用 nesteggdb 的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  nesteggdb: ^1.0.0  # 请使用最新版本

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

2. 初始化数据库

在你的 Flutter 项目中,首先需要初始化数据库。通常,你可以在 main.dart 或某个初始化函数中进行初始化。

import 'package:nesteggdb/nesteggdb.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化数据库
  await NesteggDB.initialize('my_database.db');
  
  runApp(MyApp());
}

3. 创建表

在数据库中创建表,你可以使用 execute 方法来执行 SQL 语句。

void createTable() async {
  await NesteggDB.execute('''
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT,
      age INTEGER
    )
  ''');
}

4. 插入数据

你可以使用 insert 方法来插入数据。

void insertUser(String name, int age) async {
  await NesteggDB.insert('users', {
    'name': name,
    'age': age,
  });
}

5. 查询数据

使用 query 方法来查询数据。

void getUsers() async {
  List<Map<String, dynamic>> users = await NesteggDB.query('users');
  print(users);
}

6. 更新数据

使用 update 方法来更新数据。

void updateUser(int id, String newName) async {
  await NesteggDB.update('users', {'name': newName}, where: 'id = ?', whereArgs: [id]);
}

7. 删除数据

使用 delete 方法来删除数据。

void deleteUser(int id) async {
  await NesteggDB.delete('users', where: 'id = ?', whereArgs: [id]);
}

8. 关闭数据库

在应用程序退出时,可以关闭数据库以释放资源。

void closeDatabase() async {
  await NesteggDB.close();
}

9. 使用示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 nesteggdb 进行数据库操作。

import 'package:flutter/material.dart';
import 'package:nesteggdb/nesteggdb.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NesteggDB.initialize('my_database.db');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('NesteggDB Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  await createTable();
                  print('Table created');
                },
                child: Text('Create Table'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await insertUser('John Doe', 30);
                  print('User inserted');
                },
                child: Text('Insert User'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await getUsers();
                },
                child: Text('Get Users'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await updateUser(1, 'Jane Doe');
                  print('User updated');
                },
                child: Text('Update User'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await deleteUser(1);
                  print('User deleted');
                },
                child: Text('Delete User'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

void createTable() async {
  await NesteggDB.execute('''
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT,
      age INTEGER
    )
  ''');
}

void insertUser(String name, int age) async {
  await NesteggDB.insert('users', {
    'name': name,
    'age': age,
  });
}

void getUsers() async {
  List<Map<String, dynamic>> users = await NesteggDB.query('users');
  print(users);
}

void updateUser(int id, String newName) async {
  await NesteggDB.update('users', {'name': newName}, where: 'id = ?', whereArgs: [id]);
}

void deleteUser(int id) async {
  await NesteggDB.delete('users', where: 'id = ?', whereArgs: [id]);
}
回到顶部