官方文档:https://moor.simonbinder.eu/docs/
配置:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
moor: ^4.3.2
sqlite3_flutter_libs: ^0.5.0
path_provider: ^2.0.2
# path: ^1.8.0
dev_dependencies:
flutter_test:
sdk: flutter
moor_generator: ^4.3.1
build_runner: ^2.0.5
创建:
import 'dart:io';
import 'package:moor/ffi.dart';
import 'package:moor/moor.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
// assuming that your file is called filename.dart. This will give an error at first,
// but it's needed for moor to know about the generated code
part 'moor_database.g.dart';
// this will generate a table called "todos" for us. The rows of that table will
// be represented by a class called "Todo".
class Todos extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 6, max: 32)();
TextColumn get content => text().named('body')();
IntColumn get category => integer().nullable()();
}
// This will make moor generate a class called "Category" to represent a row in this table.
// By default, "Categorie" would have been used because it only strips away the trailing "s"
// in the table name.
@DataClassName("Category")
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get description => text()();
}
LazyDatabase _openConnection() {
// the LazyDatabase util lets us find the right location for the file async.
return LazyDatabase(() async {
// put the database file, called db.sqlite here, into the documents folder
// for your app.
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(p.join(dbFolder.path, 'db.sqlite'));
return VmDatabase(file);
});
}
@UseMoor(tables: [Todos, Categories])
class MyDatabase extends _$MyDatabase {
// we tell the database where to store the data with this constructor
MyDatabase() : super(_openConnection());
// you should bump this number whenever you change or add a table definition. Migrations
// are covered later in this readme.
@override
int get schemaVersion => 1;
//增
// returns the generated id
Future<int> addTodo(TodosCompanion entry) {
return into(todos).insert(entry);
}
//删
Future feelingLazy() {
// delete the oldest nine tasks
return (delete(todos)..where((t) => t.id.isSmallerThanValue(10))).go();
}
//改
Future moveImportantTasksIntoCategory(Category target) {
// for updates, we use the "companion" version of a generated class. This wraps the
// fields in a "Value" type which can be set to be absent using "Value.absent()". This
// allows us to separate between "SET category = NULL" (`category: Value(null)`) and not
// updating the category at all: `category: Value.absent()`.
return (update(todos)..where((t) => t.title.like('%Important%'))).write(
TodosCompanion(
category: Value(target.id),
),
);
}
// Future update(Todo entry) {
// // using replace will update all fields from the entry that are not marked as a primary key.
// // it will also make sure that only the entry with the same primary key will be updated.
// // Here, this means that the row that has the same id as entry will be updated to reflect
// // the entry's title, content and category. As its where clause is set automatically, it
// // cannot be used together with where.
// return update(todos).replace(entry);
// }
//查
// loads all todo entries
Future<List<Todo>> get allTodoEntries => select(todos).get();
// watches all todo entries in a given category. The stream will automatically
// emit new items whenever the underlying data changes.
Stream<List<Todo>> watchEntriesInCategory(Category c) {
return (select(todos)..where((t) => t.category.equals(c.id))).watch();
}
}
注意:
-
part 'moor_database.g.dart';中moor_database是自己创建的文件名
- 使用命令行创建moor_database.g.dart文件
只创建一次使用:
flutter packages pub run build_runner build
一直在动态创建:
flutter packages pub run build_runner watch
出现的问题:
- Tables can't override primaryKey and use autoIncrement()
主键和自增不能同时设置,设置自增就默认是主键了
2.生成的文件变量都是final,在空安全状况下使用的时候会出现问题
解决方法:
targets:
$default:
builders:
moor_generator:
options:
mutable_classes: true