moor_flutter 1.4.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 90

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!

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();
  }
}

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: ^1.4.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';
  
Version Uploaded Documentation Archive
1.4.0 Jun 10, 2019 Go to the documentation of moor_flutter 1.4.0 Download moor_flutter 1.4.0 archive
1.3.0 Apr 20, 2019 Go to the documentation of moor_flutter 1.3.0 Download moor_flutter 1.3.0 archive
1.2.0 Mar 27, 2019 Go to the documentation of moor_flutter 1.2.0 Download moor_flutter 1.2.0 archive
1.1.0 Mar 10, 2019 Go to the documentation of moor_flutter 1.1.0 Download moor_flutter 1.1.0 archive
1.0.1 Mar 9, 2019 Go to the documentation of moor_flutter 1.0.1 Download moor_flutter 1.0.1 archive
1.0.0 Mar 9, 2019 Go to the documentation of moor_flutter 1.0.0 Download moor_flutter 1.0.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
83
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
90
Learn more about scoring.

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

  • Dart: 2.3.2
  • pana: 0.12.18
  • Flutter: 1.5.4-hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (1 direct: meta).

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.2.0 1.1.6 1.1.7
moor ^1.4.0 1.4.0+1
path >=1.0.0 <2.0.0 1.6.2
sqflite ^1.1.0 1.1.6+1
Transitive dependencies
collection 1.14.11
sky_engine 0.0.99
synchronized 2.1.0+1
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test