介绍 (Introduction)

In this article we’ll check out how to use SQLite in Flutter with the sqflite package for storing application data locally. SQLite has been around since 2000 and is a popular choice for embedding databases within local apps. For the example project, we’ll build a very simple “TODO” app that can create, update, and delete TODO items from a basic interface.

在本文中,我们将介绍如何在Flutter sqflite SQLite与sqflite包一起使用,以在本地存储应用程序数据。 SQLite自2000年以来一直存在,并且是在本地应用程序中嵌入数据库的流行选择。 对于示例项目,我们将构建一个非常简单的“ TODO”应用程序,该应用程序可以从基本界面创建,更新和删除TODO项目。

If you don’t already have Flutter, you can obtain a copy from the installation page. The source code used in this article is available here on GitHub.

如果您还没有Flutter,可以从安装页面获取副本。 本文中使用的源代码可在GitHub上找到

项目配置 (Project Configuration)

To use SQLite within a Flutter application, the first step is to include the sqflite package within the project’s pubspec.yaml like so:

要在Flutter应用程序中使用SQLite,第一步是将sqflite包包含在项目的pubspec.yaml中,如下所示:

Here we have specified sqflite version 1.2.0 or higher and path_provider at 1.6.0 or higher. Aside from this, the project is kept lean to make it easy to work with and understand.

在这里,我们将sqflite版本指定sqflite 1.2.0或更高版本,将path_provider1.6.0或更高版本。 除此之外,该项目保持精简以使其易于使用和理解。

创建一个简单的模型 (Creating a Simple Model)

To store data, a simple data model class will provide the necessary methods for converting between a SQLite-friendly data format and an object that can be used within the application. First, an abstract class called Model will serve as the base class for data models. This file is in lib/models/model.dart:

为了存储数据,一个简单的数据模型类将提供在SQLite友好的数据格式和可在应用程序内使用的对象之间进行转换的必要方法。 首先,一个名为Model的抽象类将用作数据模型的基类。 该文件在lib / models / model.dart中

The Model class is very simple and is created for convenience, to define properties / methods that can be expected from data models, such as the id as shown above. This enables the creation of one or more specific data models that will conform to this basic design pattern. For this example app, a TODO item model class is created in lib/models/todo-item.dart:

Model类非常简单,为方便起见而创建,用于定义可以从数据模型获得的属性/方法,例如上面显示的id 。 这样就可以创建一个或多个符合此基本设计模式的特定数据模型。 对于此示例应用程序,在lib / models / todo-item.dart中创建了一个TODO项目模型类:

The TodoItem class contains properties for task and complete and has a simple constructor for creating a new TODO item. For converting between instances of TodoItem and Map objects used by the database, the methods toMap and fromMap have been defined. Note that id is only added to the map when it isn’t null.

TodoItem类包含用于taskcomplete属性,并具有用于创建新的TODO项目的简单构造函数。 为了在数据库使用的TodoItem实例与Map对象之间进行转换,已定义了toMapfromMap方法。 请注意,仅当id不为null时,才会将其添加到地图。

数据库类 (Database Class)

Rather than having database logic mixed in randomly throughout the app, the main database handling methods are placed in lib/services/db.dart for convenience and ease of maintenance:

为了方便和易于维护,主要的数据库处理方法不是放在整个应用程序中随机混合数据库逻辑,而是放在lib / services / db.dart中:

This class is abstract since it isn’t meant to be instantiated and only one copy of it in memory is required. Internally, it holds a reference to the SQLite database in the _db property. The database version number has been hard-coded to 1 but in more complex applications the database version can be used to migrate database schemas up or down in version to allow rollout of new features without having to wipe the database and start from scratch.

此类是abstract因为它不是要实例化的,并且只需要在内存中复制一个即可。 在内部,它在_db属性中保存对SQLite数据库的_db 。 数据库版本号已被硬编码为1但在更复杂的应用程序中,数据库版本可用于向上或向下迁移数据库模式,以允许推出新功能而不必擦除数据库并从头开始。

An instance of the SQLite database is created within the init method, using the example database name for this project. If the example database doesn’t exist yet, onCreate is automatically called. This is where queries for creating table structure are placed. In this case, we have a todo_items table with a primary key for id along with fields that match properties on the TodoItem class above.

使用该项目的example数据库名称,在init方法中创建SQLite数据库的实例。 如果example数据库尚不存在,则会自动调用onCreate 。 在此处放置用于创建表结构的查询。 在这种情况下,我们有一个带有id主键的todo_items表,以及与上面TodoItem类的属性匹配的字段。

The query method along with insert, update, and delete are defined for performing standard CRUD operations on the database. These provide simple abstractions and allow for containing database logic within this class, which can be extremely helpful when refactoring or performing other maintenance on the app, instead of for example having to search and replace strings across multiple files or fix strange bugs that appear when making simple changes.

定义了query方法以及insert, update,delete操作,以对数据库执行标准的CRUD操作。 这些提供了简单的抽象,并允许在此类中包含数据库逻辑,这在重构或对应用程序执行其他维护时非常有帮助,而不是例如必须搜索和替换多个文件中的字符串或修复在创建时出现的奇怪错误。简单的变化。

主要申请文件 (Main Application File)

Last but not least, we have the main app logic and UX in lib/main.dart:

最后但并非最不重要的一点,我们在lib / main.dart中拥有主要的应用逻辑和UX:

This file is fairly standard for any Flutter app and defines the basic look and feel of the app along with it’s interactions. During initialization, the line WidgetsFlutterBinding.ensureInitialized() will ensure that the Flutter app initializes properly while initializing the database with await DB.init().

该文件对于任何Flutter应用程序都是相当标准的,并定义了应用程序的基本外观和交互作用。 在初始化期间,行WidgetsFlutterBinding.ensureInitialized()将确保Flutter应用正确初始化,同时使用await DB.init().初始化数据库await DB.init().

When the app starts and the MyHomePage widget is rendered, a call to refresh() pulls the todo list from the todo_items table and maps it to a List of TodoItem objects. These will be rendered within the app’s main ListView through the _items accessor, which takes the List of TodoItem objects and formats it as a list of widgets containing the todo item text and an indicator showing whether or not the item has been completed.

当应用程序启动并呈现MyHomePage小部件时,对refresh()的调用从todo_items表中提取待办事项列表,并将其映射到TodoItem对象的List 。 这些将通过_items访问器呈现在应用程序的主ListView中,该访问器获取TodoItem对象的List并将其格式化为包含待办事项文本和指示该项目是否已完成的指示器的小部件列表。

Tasks can be added by pressing the floating action button and entering a task name. When Save is pressed, the newly-created todo list item is added to the database with DB.insert. Clicking on a task in the list will toggle it between complete / incomplete states by flipping the complete boolean and storing the modified object back to the database with DB.update, and swiping a task horizontally will delete the TODO item by providing it to the DB.delete method. Whenever changes are made to the list, a call to refresh() with a subsequent setState() will ensure that the list is refreshed properly.

可以通过按浮动操作按钮并输入任务名称来添加任务。 按下“ Save ,将使用DB.insert.将新创建的待办事项列表项添加到数据库中DB.insert. 单击列表中的任务将通过翻转complete布尔值并使用DB.update,将修改后的对象存储回数据库来在完成/未完成状态之间切换DB.update,并且通过水平滑动任务将其提供给DB.delete来删除TODO项。 DB.delete方法。 每当对列表进行更改时,对带有后续setState() refresh()的调用将确保正确刷新列表。

结论 (Conclusion)

SQLite provides a convenient industry-standard way of persisting data locally within an application. This example shows how to implement basic CRUD operations for creating and manipulating simple records in a SQLite database. For more information about the sqflite plugin and the various features it supports, see this resource.

SQLite提供了一种方便的行业标准方法,可以在应用程序本地本地保存数据。 本示例说明如何实现基本的CRUD操作,以便在SQLite数据库中创建和处理简单记录。 有关sqflite插件及其支持的各种功能的更多信息,请参见此资源

Thanks for reading and good luck with your next Flutter project!

感谢您的阅读并祝您下一个Flutter项目顺利!

Image for post

Kenneth Reilly (8_bit_hacker) is CTO of LevelUP

肯尼斯·赖利( 8_bit_hacker )是LevelUP的 CTO

翻译自: https://itnext.io/how-to-use-flutter-with-sqlite-b6c75a5215c4

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐