Sub topic 14
Storing custom types with converters
This chapter assumes you have a working AppDatabase with a TodoItems table, as built in earlier chapters. You should also be comfortable with generated row classes and companions.
SQLite has only a few storage classes: integer, real, text, blob, and null. Your Dart code has richer types such as enums, lists, and value objects. A type converter is a small class that translates between the two. Drift calls it when a value is written and when a row is read, so the rest of your code only sees the Dart type.
How a converter fits in
A converter implements TypeConverter<D, S>. D is the Dart type your code uses and S is the SQL type drift stores. It has two methods: toSql runs before a value is written, and fromSql runs after a value is read.
You attach a converter to a column with .map(...). The generated row class then uses D as the field type, and the generated companion accepts D too.
Enums: the built-in shortcut
Enums are the most common custom type, so drift has two column builders for them. intEnum<T>() stores the enum's index as an integer. textEnum<T>() stores its name as text.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
enum Priority { low, normal, high }
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
IntColumn get priority =>
intEnum<Priority>().withDefault(const Constant(1))();
}
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}The default of 1 is the index of Priority.normal. Because the default is a raw SQL value, you write the stored integer here, not the enum.
After running dart run build_runner build, the generated TodoItem class has a field Priority priority. Inserts take the enum directly:
Future<int> addUrgent(String title) => into(todoItems).insert(
TodoItemsCompanion.insert(
title: title,
priority: const Value(Priority.high),
),
);The priority parameter is optional because the column has a default, so it is wrapped in Value.
Choosing between intEnum and textEnum
| Builder | Stored as | Safe to reorder values | Safe to rename values | Readability in a DB viewer |
|---|---|---|---|---|
| `intEnum<T>()` | Index (0, 1, 2) | No | Yes | Low |
| `textEnum<T>()` | Name (`'high'`) | Yes | No | High |
Neither choice is safe against every change. With intEnum, inserting a new value in the middle of the enum shifts every later index, so old rows silently map to the wrong value. With textEnum, renaming a value leaves old rows holding a name that no longer exists, and reading them throws. If you must change the enum, add new values only at the end for intEnum, and write a migration for renames with textEnum.
Writing your own converter
For anything else, extend TypeConverter. This example stores a List<String> of tags as a JSON string.
import 'dart:convert';
import 'package:drift/drift.dart';
class TagsConverter extends TypeConverter<List<String>, String> {
const TagsConverter();
@override
List<String> fromSql(String fromDb) =>
(jsonDecode(fromDb) as List).cast<String>();
@override
String toSql(List<String> value) => jsonEncode(value);
}Apply it in the table definition:
class TodoItems extends Table {
// ... other columns ...
TextColumn get tags => text()
.map(const TagsConverter())
.withDefault(const Constant('[]'))();
}Three details matter here:
- The converter has a
constconstructor, so you can pass it to.mapas a constant. - The default value is again the SQL form: the text
'[]', not an empty list. - The generated row field is
List<String> tags, and the companion takesValue<List<String>>.
Nullable columns
If a column can be null, add .nullable() after .map(...):
TextColumn get tags => text().map(const TagsConverter()).nullable()();Drift handles the null case itself. Your converter's methods never receive null, so fromSql and toSql can keep non-nullable parameter types.
Filtering on converted columns
A plain equals expects the SQL type, so t.priority.equals(Priority.high) does not compile. Columns with a converter have equalsValue, which runs the value through toSql first:
Future<List<TodoItem>> highPriorityItems() => (select(todoItems)
..where((t) => t.priority.equalsValue(Priority.high)))
.get();For other comparisons, such as "priority at least normal", you work with the stored form. With intEnum, compare against the index:
Future<List<TodoItem>> normalOrHigher() => (select(todoItems)
..where((t) => t.priority.equals(Priority.normal.index).not() |
t.priority.equals(Priority.high.index)))
.get();Use this only when you control the enum ordering. For text columns holding JSON, SQL can only match on the raw string, so filtering by an individual tag needs a LIKE match or a separate table.
Migrations with converted columns
Adding a converted column to an existing database follows the same rules as any column. The new column needs a default or must be nullable, because existing rows have no value for it. Drift's addColumn then works as usual:
@override
int get schemaVersion => 2;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.addColumn(todoItems, todoItems.priority);
}
},
);This works because the Constant(1) default is written into the ALTER TABLE statement, so every old row gets Priority.normal.
Common errors
- A
RangeErroror an unknown name when reading rows. Stored data no longer matches the enum, usually after reordering or renaming values. Fix the data with a migration. - A
FormatExceptionfromjsonDecode. A row holds text that is not valid JSON. Check that the default is'[]'and not an empty string. - A compile error on
equals. UseequalsValuefor converted columns. - Generated code not updated. After changing a converter or column, rerun
dart run build_runner build. - A converter that is not
const..mapneeds a constant instance, so give the class aconstconstructor and no mutable fields.
Exercise
You store Priority with intEnum<Priority>() and the enum is low, normal, high. A teammate changes it to low, urgent, normal, high and ships it. What goes wrong for existing users, and how would textEnum have behaved differently?
Show answer
With intEnum, the stored indexes stay the same but their meaning shifts. Rows saved as 1 (normal) now read as urgent, and rows saved as 2 (high) read as normal, with no error. With textEnum, the names 'normal' and 'high' still exist, so inserting urgent in the middle would not corrupt old rows. A rename would break textEnum rows instead.
Exercise
Write the toSql and fromSql bodies for a TypeConverter<Duration, int> that stores a Duration as whole seconds. Then say which column builder you would call .map on.
Show answer
Duration fromSql(int fromDb) => Duration(seconds: fromDb); and int toSql(Duration value) => value.inSeconds;. Call .map(const DurationConverter()) on integer(), for example IntColumn get length => integer().map(const DurationConverter())();. Sub-second precision is lost, which is a trade-off to document.