[Flutter] Using Drift to achieve Flutter data persistence

I. Introduction

Are you eager to become a Flutter expert with more tips and best practices? We have great news for you! Flutter from zero to one basic entry to the application line of the whole strategy is waiting for you to join! This column contains all the resources you need to learn Flutter, including code samples and in-depth analysis. The content of the column will continue to be updated, and the price will increase accordingly. Join now and enjoy the best price! In addition, we also have a dedicated discussion group, you can click here to join our discussion group to communicate and learn with other Flutter learners. Let's start our Flutter learning journey today!

When developing Flutter applications, we often need to deal with the storage and reading of data. Drift provides an elegant solution to this problem. Drift is a reactive persistence library for Flutter and Dart, built on top of sqlite, allowing us to manipulate databases in a type-safe, easy-to-understand manner.

In this article, we'll cover the basics of using Drift, including how to install and set up Drift, how to create databases and tables, and how to insert, query, update, and delete data. We'll also cover how to use transactions to ensure data consistency.

After reading this article, you will be able to master the following knowledge:

  • Understand the basic concepts and functions of Drift
  • Learn how to install and setup Drift in a Flutter project
  • Learn how to create databases and tables with Drift
  • Learn how to insert, query, update and delete data with Drift
  • Learn how to use Drift for transactions

This is the blog published by Xiaoyu Youth on CSDN in 2023. Due to the rampant copyright infringement of the collection station, if you do not see this article on CSDN, please contact me through CSDN, thank you for your support~

insert image description here

2. Version information

Before we start, we need to make sure our development environment meets the following requirements:

  • Flutter version: 3.10.0 or higher
  • Dart SDK version: 3.0.0 or higher
  • Drift version: 2.9.0

Please make sure your Flutter and Dart SDK versions meet the above requirements. If your version is lower than these requirements, you may need to upgrade your development environment. You can check your Flutter and Dart SDK versions by running flutter --versionand .dart --version

3. Introduction to Drift

Drift is a reactive persistence library for Flutter and Dart, built on top of sqlite. Drift has the following features:

  • Flexible: Drift allows you to write queries in both SQL and Dart, providing a fluent API for both languages. You can filter and sort results, or use joins to run queries on multiple tables. You can even use complex sql features such as WITH and WINDOW clauses.
  • Feature-rich: Drift has built-in support for transactions, schema migrations, complex filters and expressions, batch updates, and joins. We even have a built in SQL IDE!
  • Modularity: Drift helps you simplify your database code thanks to built-in support for imports in daos and sql files.
  • Safety: Drift generates type-safe code based on your tables and queries. If you make a mistake in your query, Drift will find it at compile time and provide helpful and descriptive hints.
  • Fast: Although Drift lets you write powerful queries, it can keep up with the performance of key-value stores. Drift is the only major persistence library with built-in threading support, allowing you to run your database code in isolation without any extra effort.
  • Reactive: Turn any sql query into an auto-updating stream! This includes complex queries across multiple tables.
  • Cross-platform support: Drift works on Android, iOS, macOS, Windows, Linux and the web. This template is a Flutter todo app that works on all platforms.
  • Battle-tested and production-ready: Drift is stable and undergoes extensive unit and integration testing. It powers production Flutter apps.

4. How to install and set up Drift

To use Drift in a Flutter project, we first need to add it to our project dependencies. Open your pubspec.yamlfile, find dependenciesthe section, and add the following code:

dependencies:
  flutter:
    sdk: flutter

  drift: ^2.9.0

Then, run flutter packages getthe command to fetch the package.

Next, we need to create a Dart file to define our database. In this file, we will define our tables and data access objects (DAO).

import 'package:drift/drift.dart';

part 'my_database.g.dart';

class Tasks extends Table {
    
    
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text().withLength(min: 1, max: 50)();
  BoolColumn get completed => boolean().withDefault(Constant(false))();
}

(tables: [Tasks])
class MyDatabase extends _$MyDatabase {
    
    
  MyDatabase(QueryExecutor e) : super(e);

  
  int get schemaVersion => 1;
}

In this example, we define a Taskstable with three fields: id, nameand completed. Then, we define a MyDatabaseclass that contains our Taskstable.

5. Basic use

1. Create database and tables

In the previous chapter, we have MyDatabasedefined Tasksthe table in the class. Now, we need to create a database instance and use this instance to manipulate our Taskstables.

First, we need to create one QueryExecutor. QueryExecutoris the interface that Drift uses to interact with SQLite databases. On Android and iOS, we usually use FlutterQueryExecutor, which creates a SQLite database in the app's sandbox directory.

final executor = FlutterQueryExecutor.inDatabaseFolder(
  path: 'db.sqlite',
  logStatements: true,
);

Then, we use this QueryExecutorto create MyDatabasean instance of :

final db = MyDatabase(executor);

Now, we can use dbto manipulate our Taskstable.

2. Insert, query, update and delete data

In Drift, we can use intothe method to insert data, use watchthe or getmethod to query data, use updatethe method to update data, and use deletethe method to delete data.

// 插入数据
final task = TasksCompanion(
  name: Value('Learn Drift'),
  completed: Value(false),
);
await into(tasks).insert(task);

// 查询数据
final allTasks = await select(tasks).get();

// 更新数据
final completedTask = TasksCompanion(
  id: Value(1),
  completed: Value(true),
);
await update(tasks).replace(completedTask);

// 删除数据
await delete(tasks).delete(completedTask);

In these examples, we use TasksCompanionto create a new task, and then use into(tasks).insert(task)to insert this task. We use select(tasks).get()to get all tasks. We use update(tasks).replace(completedTask)to update a task. We use delete(tasks).delete(completedTask)to delete a task.

3. Using transactions

Transactions are a very important concept in database operations. Transactions can ensure that a series of operations either all succeed or all fail, thus ensuring data consistency.

In Drift, we can use transactionthe method to execute a transaction. Here is an example:

await db.transaction(() async {
    
    
  // 插入一个新的任务
  final task = TasksCompanion(
    name: Value('Learn Drift'),
    completed: Value(false),
  );
  await into(tasks).insert(task);

  // 更新一个任务
  final completedTask = TasksCompanion(
    id: Value(1),
    completed: Value(true),
  );
  await update(tasks).replace(completedTask);
});

We insert a new task and update a task in one transaction. If either of these two operations fails, neither operation will be performed.

6. Summary

In this article, we introduced how to use Drift for data persistence in a Flutter project. We learned how to install and set up Drift, how to create databases and tables, how to insert, query, update, and delete data, and how to use transactions.

Hope this article helps you understand and use Drift. If you have any questions or suggestions, please leave a message in the comment area.

This is the blog published by Xiaoyu Youth on CSDN in 2023. Due to the rampant copyright infringement of the collection station, if you do not see this article on CSDN, please contact me through CSDN, thank you for your support~

In the next article, we'll dive into Drift's advanced features, including SQL and Dart queries, complex SQL features, schema migrations, complex filters and expressions, batch updates and joins, type-safe code generation, performance optimizations, and Threading support, reactive programming, and automatically updated streams. Stay tuned!

Are you curious about Flutter and want to learn more about it? Then, Flutter from zero to one basic introduction to application launch guide will be your best choice! Here, you can find comprehensive Flutter learning resources, including code samples and in-depth analysis. Are you wondering how to build apps with Flutter? All the answers are in our column! Don't hesitate anymore, the content of the column will continue to be updated, and the price will increase accordingly. Join now and enjoy the best price! Let's explore the world of Flutter together! Want to know more? Click here to view the Flutter Developer 101 Getting Started booklet column guide . In addition, we also have a dedicated discussion group, you can click here to join our discussion group to communicate and learn with other Flutter learners.

おすすめ

転載: blog.csdn.net/diandianxiyu/article/details/131605795