moor_flutter 2.0.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 98

Moor #

Moor is an easy to use, reactive persistence library for Flutter apps. Define your database tables in pure Dart and enjoy a fluent query API, auto-updating streams and more!

Here are just some of the many features moor provides to make dealing with persistence much easier:

Declarative tables #

With moor, you can declare your tables in pure dart without having to miss out on advanced sqlite features. Moor will take care of writing the CREATE TABLE statements when the database is created.

Fluent queries #

Thanks to the power of Dart build system, moor will let you write typesafe queries:

Future<User> userById(int id) {
  return (select(users)..where((user) => user.id.equals(id))).getSingle();
  // runs SELECT * FROM users WHERE id = ?, automatically binds the parameter
  // and parses the result row.
}

No more hard to debug typos in sql, no more annoying to write mapping code - moor takes care of all the boring parts. Moor supports features like order by statements, limits and even joins with this api.

Prefer SQL? Moor got you covered #

Moor contains a powerful sql parser and analyzer, allowing it to create typesafe APIs for all your sql queries:

@UseMoor(
  tables: [Categories],
  queries: {
    'categoryById': 'SELECT * FROM categories WHERE id = :id'
  },
)
class MyDatabase extends _$MyDatabase {
// the _$MyDatabase class will have the categoryById(int id) and watchCategoryById(int id)
// methods that execute the sql and parse its result into a generated class.

All queries are validated and analyzed during build-time, so that moor can provide hints about potential errors quickly and generate efficient mapping code once.

Auto-updating streams #

For all your queries, moor can generate a Stream that will automatically emit new results whenever the underlying data changes. This is first-class feature that perfectly integrates with custom queries, daos and all the other features. Having an auto-updating single source of truth makes managing perstistent state much easier!

And much moor... #

Moor also supports transactions, DAOs, powerful helpers for migrations, batched inserts and many more features that makes writing persistence code much easier.

Getting started #

For a more detailed guide on using moor, check out the documentation.

Adding the dependency #

First, add moor to your project's pubspec.yaml.

dependencies:
  moor_flutter: # use the latest version

dev_dependencies:
  moor_generator: # use the latest versions
  build_runner: 

Declaring tables #

You can use the DSL included with this library to specify your libraries with simple dart code:

import 'package:moor_flutter/moor_flutter.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 'filename.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: 10)();
  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()();
}

// this annotation tells moor to prepare a database class that uses both of the
// tables we just defined. We'll see how to use that database class in a moment.
@UseMoor(tables: [Todos, Categories])
class MyDatabase {
  
}

⚠️ Note: The column definitions, the table name and the primary key must be known at compile time. For column definitions and the primary key, the function must use the => operator and can't contain anything more than what's included in this readme and the examples. Otherwise, the generator won't be able to know what's going on.

Generating the code #

Moor integrates with the dart build system, so you can generate all the code needed with flutter packages pub run build_runner build. If you want to continuously rebuild the generated code whenever you change your code, run flutter packages pub run build_runner watch instead. After running either command once, the moor generator will have created a class for your database and data classes for your entities. To use it, change the MyDatabase class as follows:

@UseMoor(tables: [Todos, Categories])
class MyDatabase extends _$MyDatabase {
  // we tell the database where to store the data with this constructor
  MyDatabase() : super(FlutterQueryExecutor.inDatabaseFolder(path: 'db.sqlite'));

  // 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; 
}

You can ignore the schemaVersion at the moment, the important part is that you can now run your queries with fluent Dart code:

Writing queries #

// inside the database class:

  // 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<TodoEntry>> watchEntriesInCategory(Category c) {
    return (select(todos)..where((t) => t.category.equals(c.id))).watch();
  }
}

Visit the detailed documentation to learn about advanced features like transactions, DAOs, custom queries and more.

2.0.0 #

See the changelog of moor for details, or check out an overview of new features here

1.7.0 #

  • Support custom columns via type converters. See the docs for details on how to use this feature.
  • Transactions now roll back when not completed successfully, they also rethrow the exception to make debugging easier.
  • New backends api, making it easier to write database drivers that work with moor. Apart from moor_flutter, new experimental backends can be checked out from git:
    1. encrypted_moor: An encrypted moor database: https://github.com/simolus3/moor/tree/develop/extras/encryption
    2. moor_mysql: Work in progress mysql backend for moor. https://github.com/simolus3/moor/tree/develop/extras/mysql
  • The compiled sql feature is no longer experimental and will stay stable until a major version bump
  • New, experimental support for .moor files! Instead of declaring your tables in Dart, you can choose to declare them with sql by writing the CREATE TABLE statement in a .moor file. You can then use these tables in the database and with daos by using the include parameter on @UseMoor and @UseDao. Again, please notice that this is an experimental api and there might be some hiccups. Please report any issues you run into.

1.6.0 #

  • Experimental web support! See the documentation for details.
  • Make transactions easier to use: Thanks to some Dart async magic, you no longer need to run queries on the transaction explicitly. This
    Future deleteCategory(Category category) {
      return transaction((t) async {
        await t.delete(categories).delete(category);
      });
    }
    
    is now the same as this (notice how we don't have to use the t. in front of the delete)
      Future deleteCategory(Category category) {
        return transaction((t) async {
          await delete(categories).delete(category);
        });
      }
    
    This makes it much easier to compose operations by extracting them into methods, as you don't have to worry about not using the t parameter.
  • Moor now provides syntax sugar for list parameters in compiled custom queries (SELECT * FROM entries WHERE id IN ?)
  • Support COLLATE expressions.
  • Date time columns are now comparable
  • The StringType now supports arbitrary data from sqlite (#70). Thanks, knaeckeKami!
  • Bugfixes related to stream queries and LIMIT clauses.

1.5.0 #

This version introduces some new concepts and features, which are explained in more detail below. Here is a quick overview of the new features:

  • More consistent and reliable callbacks for migrations. You can now use MigrationStrategy.beforeOpen to run queries after migrations, but before fully opening the database. This is useful to initialize data.
  • Greatly expanded documentation, introduced additional checks to provide more helpful error messages
  • New getSingle and watchSingle methods on queries: Queries that you know will only return one row can now be instructed to return the value directly instead of wrapping it in a list.
  • New "update companion" classes to clearly separate between absent values and explicitly setting values back to null - explained below.
  • Experimental support for compiled sql queries: Moor can now generate typesafe APIs for written sql. Read on to get started.

Update companions #

Newly introduced "Update companions" allow you to insert or update data more precisely than before. Previously, there was no clear separation between "null" and absent values. For instance, let's say we had a table "users" that stores an id, a name, and an age. Now, let's say we wanted to set the age of a user to null without changing its name. Would we use User(age: null)? Here, the name column would implicitly be set to null, so we can't cleanly separate that. However, with UsersCompanion(age: Value(null)), we know the difference between Value(null) and the default Value.absent().

Don't worry, all your existing code will continue to work, this change is fully backwards compatible. You might get analyzer warnings about missing required fields. The migration to update companions will fix that. Replacing normal classes with their update companions is simple and the only thing needed to fix that. The documentation has been updated to reflect this. If you have additional questions, feel free to create an issue.

Compiled sql queries #

Experimental support for compile time custom statements. Sounds super boring, but it actually gives you a fluent way to write queries in pure sql. The moor generator will figure out what your queries return and automatically generate the boring mapping part. Head on to the documentation to find out how to use this new feature.

Please note that this feature is in an experimental state: Expect minor, but breaking changes in the API and in the generated code. Also, if you run into any issues with this feature, reporting them would be super appreciated.

1.4.0 #

  • Added the RealColumn, which stores floating point values
  • Better configuration for the serializer with the JsonKey annotation and the ability to use a custom ValueSerializers

1.3.0 #

  • Moor now supports table joins
    • Added table aliases
  • Default values for columns: Just use the withDefault method when declaring a column
    • added expressions that resolve to the current date or time
  • Fixed a crash that would occur if the first operation was a transaction
  • Better support for custom expressions as part of a regular query
  • Faster hashcode implementation in generated data classes

1.2.0 #

Changes from the moor and moor_generator libraries:

  • Breaking: Generated DAO classes are now called _$YourNameHere, it used to be just _YourNameHere (without the dollar sign)
  • Blob data type
  • insertOrReplace method for insert statements
  • DAOs can now operate on transactions
  • Custom constraints
  • Query streams are now cached so that equal queries yield identical streams. This can improve performance.
  • Generated classes now use lazy getters instead of recalculating fields on each access
  • Data classes can be converted from and to json

1.1.0 #

  • Transactions

1.0.0 #

  • Initial release

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:moor_example/bloc.dart';
import 'widgets/homescreen.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return MyAppState();
  }
}

// We use this widget to set up the material app and provide an InheritedWidget that
// the rest of this simple app can then use to access the database
class MyAppState extends State<MyApp> {
  TodoAppBloc bloc;

  @override
  void initState() {
    bloc = TodoAppBloc();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: bloc,
      child: MaterialApp(
        title: 'moor Demo',
        theme: ThemeData(
          primarySwatch: Colors.orange,
          // use the good-looking updated material text style
          typography: Typography(
            englishLike: Typography.englishLike2018,
            dense: Typography.dense2018,
            tall: Typography.tall2018,
          ),
        ),
        home: HomeScreen(),
      ),
    );
  }
}

class BlocProvider extends InheritedWidget {
  final TodoAppBloc bloc;

  BlocProvider({@required this.bloc, Widget child}) : super(child: child);

  @override
  bool updateShouldNotify(BlocProvider oldWidget) {
    return oldWidget.bloc != bloc;
  }

  static TodoAppBloc provideBloc(BuildContext ctx) =>
      (ctx.inheritFromWidgetOfExactType(BlocProvider) as BlocProvider).bloc;
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  moor_flutter: ^2.0.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:moor_flutter/moor_flutter.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
96
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
98
Learn more about scoring.

We analyzed this package on Dec 14, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.0
  • pana: 0.13.1+4
  • Flutter: 1.12.13+hotfix.4

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
flutter 0.0.0
meta ^1.0.0 1.1.8
moor ^2.0.0 2.1.1
path ^1.0.0 1.6.4
sqflite ^1.1.6+5 1.1.8 1.2.0-dev.1
Transitive dependencies
charcode 1.1.2
collection 1.14.11 1.14.12
convert 2.1.1
pedantic 1.9.0
sky_engine 0.0.99
synchronized 2.1.1
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test