Orientação gerada a partir de informações públicas. Apenas para referência.
Floor é uma abstração SQLite segura por tipo, reativa e leve projetada para aplicativos Flutter. Oferece uma maneira limpa e segura em tempo de compilação de interagir com bancos de dados SQLite usando anotações e geração de código. O Floor simplifica operações de banco de dados com DAOs (Objetos de Acesso a Dados) fáceis de usar e suporta consultas reativas por meio de streams. Construído para desempenho e experiência do desenvolvedor, integra-se perfeitamente em projetos Flutter sem exigir escrita manual de SQL. A biblioteca garante segurança de tipo e reduz erros em tempo de execução validando esquemas de banco de dados em tempo de compilação.
Casos de uso
Armazenamento de dados offline em aplicativos móveis
Sincronização de dados em tempo real com banco de dados local
Gerenciar dados estruturados de aplicativos, como perfis de usuários ou configurações
Construindo aplicativos com foco em offline
Armazenando respostas de API em cache
Rastrear registros de atividade do usuário
Principais recursos
Definições de esquema de banco de dados tipadas
Consultas reativas por meio de fluxos
Geração de código para DAOs
Validação em tempo de compilação da estrutura do banco de dados
Desempenho leve e rápido
Integração fácil com o gerenciamento de estado do Flutter
Indicado para
Desenvolvedores construindo aplicativos Flutter com capacidade offline
Equipes priorizando segurança de tipo e manutenibilidade
Projetos que exigem persistência de dados local eficiente
Aplicativos que precisam de atualizações em tempo real a partir de dados locais
Desenvolvedores Flutter em busca de boilerplate mínimo
Considerações
Requer configuração de geração de código
Limitado ao SQLite como banco de dados subjacente
Sem suporte embutido para junções complexas ou SQL bruto
O manuseio de migração exige planejamento cuidadoso
Não adequado para bancos de dados do lado do servidor em grande escala
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Floor provides a neat SQLite abstraction for your Flutter applications inspired by the Room persistence library.
It comes with automatic mapping between in-memory objects and database rows while still offering full control of the database with the use of SQL.
As a consequence, it's necessary to have an understanding of SQL and SQLite in order to harvest Floor's full potential.
null-safe
typesafe
reactive
lightweight
SQL centric
no hidden magic
no hidden costs
iOS, Android, Linux, macOS, Windows
⚠️ The library is open to contributions!
Refer to GitHub Discussions for questions, ideas, and discussions.
Getting Started
1. Setup Dependencies
Add the runtime dependency floor as well as the generator floor_generator to your pubspec.yaml.
The third dependency is build_runner which has to be included as a dev dependency just like the generator.
floor holds all the code you are going to use in your application.
floor_generator includes the code for generating the database classes.
build_runner enables a concrete way of generating source code files.
It will represent a database table as well as the scaffold of your business object.
@entity marks the class as a persistent class.
It's required to add a primary key to your table.
You can do so by adding the @primaryKey annotation to an int property.
There is no restriction on where you put the file containing the entity.
This component is responsible for managing access to the underlying SQLite database.
The abstract class contains the method signatures for querying the database which have to return a Future or Stream.
You can define queries by adding the @Query annotation to a method.
The SQL statement has to get added in parenthesis.
The method must return a Future or Stream of the Entity you're querying for.
@insert marks a method as an insertion method.
// dao/person_dao.dartimport'package:floor/floor.dart';
@daoabstractclassPersonDao{
@Query('SELECT * FROM Person')
Future<List<Person>> findAllPeople();
@Query('SELECT name FROM Person')
Stream<List<String>> findAllPeopleName();
@Query('SELECT * FROM Person WHERE id = :id')
Stream<Person?> findPersonById(int id);
@insertFuture<void> insertPerson(Person person);
}
4. Create the Database
It has to be an abstract class which extends FloorDatabase.
Furthermore, it's required to add @Database() to the signature of the class.
Make sure to add the created entity to the entities attribute of the @Database annotation.
In order to make the generated code work, it's required to also add the listed imports.
Make sure to add part 'database.g.dart'; beneath the imports of this file.
It's important to note that 'database' has to get exchanged with the filename of the database definition.
In this case, the file is named database.dart.
// database.dart// required package importsimport'dart:async';
import'package:floor/floor.dart';
import'package:sqflite/sqflite.dart'as sqflite;
import'dao/person_dao.dart';
import'entity/person.dart';
part'database.g.dart'; // the generated code will be there@Database(version: 1, entities: [Person])
abstractclassAppDatabaseextendsFloorDatabase{
PersonDaoget personDao;
}
5. Run the Code Generator
Run the generator with flutter packages pub run build_runner build.
To automatically run it, whenever a file changes, use flutter packages pub run build_runner watch.
6. Use the Generated Code
For obtaining an instance of the database, use the generated $FloorAppDatabase class, which allows access to a database builder.
The name is being composed by $Floor and the database class name.
The string passed to databaseBuilder() will be the database file name.
For initializing the database, call build() and make sure to await the result.
In order to retrieve the PersonDao instance, invoking the persoDao getter on the database instance is enough.
Its functions can be used as shown in the following snippet.
final database = await $FloorAppDatabase.databaseBuilder('app_database.db').build();
final personDao = database.personDao;
final person = Person(1, 'Frank');
await personDao.insertPerson(person);
final result = await personDao.findPersonById(1);
For further examples take a look at the example and test directories.
Naming
The library's name derives from the following.
Floor as the bottom layer of a Room which points to the analogy of the database layer being the bottom and foundation layer of most applications.
Where fl also gives a pointer that the library is used in the Flutter context.
Copyright 2023 The Floor Project Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.