flutter数据库_为Flutter应⽤选择正确的数据库
flutter 数据库
This article was originally published on the Codemagic blog
本⽂最初发布Codemagic博客上
There are a lot of options out there today when it comes to databases in your application. They typically fit into these three categories:
对于应⽤程序中的数据库,今天有很多选择。 它们通常适合以下三类:
Relational — these are the databases in the traditional sense. They don’t just store data but also the relationships between the data. SQLite is an example of a relational database.
关系式 -这些是传统意义上的数据库。 它们不仅存储数据,还存储数据之间的关系 。 SQLite是关系数据库的⼀个⽰例。
NoSQL — these databases store data as documents. A schema is not enforced as is the case with a relational database.
They are lightning-quick and handle huge unstructured pieces of data very well. MongoDB is an example of a NoSQL database.
NoSQL-这些数据库将数据存储为⽂档 。 与关系数据库不同,没有强制执⾏架构。 它们闪电般迅捷 ,可以很好地处理⼤量⾮结构化数据。 MongoDB是NoSQL数据库的⽰例。
Individually tailored data storage — while this option is not technically a database, you don’t have to use the above solutions. You can store your data in a JSON file and handle the serialisation and deserialisation yourself. This would be incredibly fast but would open you up to some weird bugs if you weren’t a programming genius.
量⾝定制的数据存储 -尽管从技术上讲该选项不是数据库,但您不必使⽤上述解决⽅案。 您可以将数据存储在JSON⽂件中,并亲⾃处理序列化和反序列化。 这将是⾮常快的,但是如果您不是编程天才,则会使您遇到⼀些奇怪的错误。
By the end of this article, you will know:
到本⽂结尾,您将知道:
The basics of how each database works.
每个数据库的⼯作原理。
How to get set up with each database. ⚙
如何建⽴每个数据库。 ⚙
What a good use case would be for each database.
每个数据库都有⼀个很好的⽤例。
In this article, we’ll divide our database types according to the three categories mentioned above.
在本⽂中,我们将根据上述三个类别来划分数据库类型。
关系型 (Relational)
Relational databases have been around for a very long time (since 1970, according to a quick Google search). Let’s look at some of the options you have on Flutter for relational databases today.
关系数据库已经存在很长时间了(根据Google的快速搜索,⾃1970年以来)。 让我们看看您在Flutter上为关系数据库所拥有的⼀些选项。()
SQflite is an implementation of SQLite for Flutter. It affords you complete control over your database, queries, relationships, everything you could wish for.
SQflite是SQLite for Flutter的实现。 它使您可以完全控制数据库,查询,关系以及所有想要的东西。
Interacting with a SQLite database in Flutter looks like this ():
在Flutter中与SQLite数据库进⾏交互看起来像这样( ):
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
// Delete the database
await deleteDatabase(path);
// open the database
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
ute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});Inserting data follows the same age-old SQLite tenants  // Insert some records in a transaction
ansaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
print('inserted1: $id1');
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
print('inserted2: $id2');
});
And querying happens like this:
查询发⽣如下:
// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
优点  (Pros  )
Total control over the database.
完全控制数据库。
A very efficient SQLite database for your app (given that you have pre-existing SQLite knowledge).
适⽤于您应⽤的⾼效SQLite数据库(前提是您已具备SQLite知识)。
Easily read by third party apps that can open SQLite databases (so you can open the database on your computer and see what the data looks like).
可以打开SQLite数据库的第三⽅应⽤程序可以轻松读取(因此您可以在计算机上打开数据库,查看数据是什么样的)。
缺点  (Cons  )
Writing out all your queries by hand can take a lot of time.
⼿⼯写出所有查询会花费很多时间。
Returned data from the database isn’t strongly typed from the start.
从数据库开始返回的数据从⼀开始就不是强类型的。
It is potentially difficult to handle migrations on the device (when the schema changes between version updates for instance).
处理设备上的迁移可能很困难(例如,当模式在版本更新之间更改时)。
It has no support for web.
它不⽀持⽹络。
⽤例 (Use case)
SQFlite is good when you need relational data but also fine-grained control over the actual queries. If you’re comfortable with writing your own queries and don’t mind writing both a lot of queries and the code to convert the results to and from your classes, this could be a good fit for you.
当您需要关系数据时,SQFlite是很好的选择,⽽且还可以对实际查询进⾏细粒度的控制。 如果您对编写⾃⼰的查询感到满意,并且不介意编写⼤量查询和将结果与类进⾏相互转换的代码,那么这可能⾮常适合您。
SQLite抽象 (SQLite abstractions)
Directly using SQLite to manage your application database can be quite powerful but also unwieldy. That’s why there are so many solutions that abstract some of the functionality from SQLite into more e
asily used functionality. These abstractions can make a SQLite database easier to use, while still retaining a lot of the benefits of SQLite.
直接使⽤SQLite管理您的应⽤程序数据库可能⾮常强⼤,但也很⿇烦。 这就是为什么有这么多解决⽅案将SQLite的某些功能抽象为更易于使⽤的功能的原因。 这些抽象可以使SQLite数据库更易于使⽤,同时仍然保留SQLite的许多优点。
and are fairly popular examples of this approach. In this article we’ll look at Moor, but the approach that these two packages take in abstracting SQLite is fairly similar.
和是这种⽅法相当受欢迎的⽰例。 在本⽂中,我们将探讨Moor,但是这两个软件包在抽象SQLite中所采⽤的⽅法⾮常相似。
泊 (Moor)
In order to use Moor, we import the Moor package from , but we also have to import something called the moor_generator. This is used by build_runner to generate the code to use the database.
为了使⽤Moor,我们从导⼊了Moor包,但是我们还必须导⼊⼀个称为moor_generator东西。 build_runner使⽤build_runner来⽣成使⽤数据库的代码。
Why do we use build_runner? build_runner is primarily used to generate code for your Flutter projects. Before I came to Flutter, I rarely, if ever, had to use a code generation utility. The main reason for this is because most other languages that I had used up until this point (such as C#) supported reflection.
为什么我们使⽤ build_runner?build_runner主要⽤于为Flutter项⽬ ⽣成代码 。在来Flutter之前,我很少(如果有的话)必须使⽤代码⽣成实⽤程序。这样做的主要原因是因为到⽬前为⽌我⽤尽的其他⼤多数语⾔(例如C#)都⽀持 反射 。
Simply put, this makes it possible for the framework to dynamically invoke parts of the program at runtime. It’s quite powerful, but typically it can be quite slow. It also affects linking of the produced application, as with reflection,
technically every part of your application could be accessed or used.
简⽽⾔之,这使框架可以在运⾏时动态调⽤程序的各个部分。它功能强⼤,但通常速度可能很慢。它也影响⽣成的应⽤程序的 链接,就像反射⼀样,从技术上讲,您的应⽤程序的每个部分都可以访问或使⽤。
When packages use functionality that typically were provided by reflection, they usually use build_runn
er to generate the necessary code ahead of time. This results in faster code execution at runtime, and also results in better ‘tree shaking’, or minimisation of the application binary at deployment time.
当程序包使⽤通常由反射提供的功能时,它们通常使⽤build_runner提前⽣成必要的代码。这样可以在运⾏时更快地执⾏代码,还可以在部署时更好地“摇树”或最⼩化应⽤程序⼆进制⽂件。
A look into the helps us understand the way a database is created.
查看“ 可帮助我们了解创建数据库的⽅式。
import 'package:moor/moor.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 '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: 32)();
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 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 tables
// we just defined. We'll see how to use that database class in a moment.
@UseMoor(tables: [Todos, Categories])
class MyDatabase {
}
Moor programatically creates the schema for your tables depending on how you define their contents. In the beginning of this code example, we can see the part statement. When we run the build_runner command, moor generates the schema based on what we have defined in this file. You can also drop back to raw SQL at any time if you need to run a specific query or if you want more fine-grained control.
Moor通过编程⽅式为您的表创建架构,具体取决于您定义表内容的⽅式。 在此代码⽰例的开头,我们可以看到part语句。 当我们运
⾏build_runner命令时, moor根据我们在此⽂件中定义的内容⽣成架构。 如果需要运⾏特定查询或需要更细粒度的控制,则还可以随时返回原始SQL。flutter开发app
优点  (Pros  )
Strongly typed results!
强类型结果!
Based on SQLite.
基于SQLite。
You don’t have to manually construct every query by hand.
您不必⼿动构造每个查询。
A lot of the heavy lifting is handled by code generation.
许多繁重的⼯作由代码⽣成处理。
SQLite database can be navigated with a wide range of tools available today to check data during development.
可以使⽤当今可⽤的各种⼯具来浏览SQLite数据库,以在开发期间检查数据。
缺点  (Cons  )
It can be cumbersome to handle schema updates on the local device.
在本地设备上处理架构更新可能很⿇烦。
Web support is still in preview.
Web⽀持仍在预览中。
It has platform-specific dependencies (not written in pure Dart).
它具有特定于平台的依赖性(不是⽤纯Dart编写的)。
⽤例 (Use case)
If you still need relational data but want to write as little SQL as possible (if you are used to Entity Framework, for instance), this could be a good fit for you.
如果您仍然需要关系数据,但想编写SQL越少越好(例如,如果您习惯使⽤Entity Framework),那么这可能是您的理想选择。NoSQL (NoSQL)
There are quite a few options when it comes to NoSQL databases for Flutter as well. We have the heavy hitters that have been around for a long time like Firebase, as well as the newer solutions like Hive. There are many differences between Hive and Firebase but perhaps the main difference is that one can sync to an online store (Firebase), whereas the other is more adequately suited for storing locally on the device (Hive).
Flutter的NoSQL数据库也有很多选择。 我们拥有像Firebase这样已经存在很长时间的沉重打击者,以及像Hive这样的较新解决⽅案。Hive和Firebase之间有许多区别,但也许主要区别在于,⼀个可以同步到在线商店(Firebase),⽽另⼀个更适合于在设备上本地存储(Hive)。
Firebase —在线NoSQL存储 (Firebase — online NoSQL storage)
Firebase is a traditional document storage database. You store data in collections that are like tables in a traditional database. These collections store documents. Documents store data types, like string, int, etc. They can also store a link to another document, so even though Firebase isn't strictly relational you can still create relationships between your data.
Firebase是传统的⽂档存储数据库。 您将数据存储在类似于传统数据库中表的集合中。 这些集合存储⽂档 。 ⽂档存储数据类型,例
如string , int等。它们还可以存储指向另⼀个⽂档的链接,因此,即使Firebase不是严格关系的,您仍然可以在数据之间创建关系。
The setup for Firebase is quite involved compared to other on-device options, like Moor or Hive, but you get
synchronisation of data between clients and the server. This means that if you have multiple clients with an app and they are all interacting with the same data, then this data can be kept in sync between these clients. Also, this setup is covered quite well in a . The only downside of this approach is that you don’t get strongly typed data in the same way as you do with Moor or Hive. You have to handle this yourself.
与其他设备上选项(例如Moor或Hive)相⽐,Firebase的设置相当复杂,但是您可以在客户端和服务器之间实现数据同步 。 这意味着,如果您有⼀个应⽤程序有多个客户端,并且它们都与同⼀数据进⾏交互,则可以使这些客户端之间的数据保持同步。 另外, 的很好地介绍了此设置。 这种⽅法的唯⼀缺点是,您不会像使⽤Moor或Hive那样获得强类型数据。 您必须⾃⼰处理。
优点  (Pros  )
Synchronises with Firebase online in a near real-time fashion.
以近乎实时的⽅式与Firebase在线同步。
Great tooling support.
强⼤的⼯具⽀持。
Easy to browse data online via the Firebase Console.
通过Firebase控制台轻松在线浏览数据。
缺点  (Cons  )
Firebase setup can be complicated if you don’t already have it added to your app.
如果您尚未将Firebase安装添加到应⽤程序中,则可能会很复杂。
As the database is online, you need to be mindful of a lot more than a strictly on-device database (like access

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。