패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.5.0

floor

Flutter 애플리케이션용 타입 안전하고 반응형이며 가벼운 SQLite 추상화입니다. 이 라이브러리는 런타임 종속성입니다.

30일 다운로드
3.2만
좋아요
1천
Pub 점수
110

패키지 설치

flutter pub add floor

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Floor는 Flutter 애플리케이션을 위한 타입 안전하고 반응형이며 가벼운 SQLite 추상화입니다. 어노테이션과 코드 생성을 사용하여 컴파일 시 안전한 방식으로 SQLite 데이터베이스와 상호작용할 수 있도록 제공합니다. Floor는 사용하기 쉬운 DAO(Data Access Object)를 통해 데이터베이스 작업을 간소화하며, 스트림을 통한 반응형 쿼리를 지원합니다. 성능과 개발자 경험을 고려해 설계되었으며, 수동 SQL 작성 없이 Flutter 프로젝트에 원활하게 통합됩니다. 라이브러리는 컴파일 시 데이터베이스 스키마를 검증함으로써 타입 안전성을 보장하고 런타임 오류를 줄입니다.

사용 사례

  • 모바일 앱에서의 오프라인 데이터 저장
  • 로컬 데이터베이스와의 실시간 데이터 동기화
  • 사용자 프로필 또는 설정과 같은 구조화된 앱 데이터 관리
  • 오프라인 우선 애플리케이션 빌드
  • 캐시된 API 응답 저장
  • 사용자 활동 로그 추적

주요 기능

  • 타입 안전한 데이터베이스 스키마 정의
  • 스트림을 통한 반응형 쿼리
  • DAO에 대한 코드 생성
  • 데이터베이스 구조의 컴파일 시 검증
  • 경량이고 빠른 성능
  • Flutter 상태 관리와의 간편한 통합

적합한 대상

  • 오프라인 기능을 갖춘 플러터 앱을 개발하는 개발자
  • 유형 안전성과 유지보수를 우선시하는 팀
  • 효율적인 로컬 데이터 지속성을 필요로 하는 프로젝트
  • 로컬 데이터에서 실시간 업데이트가 필요한 앱
  • 최소한의 보일러플레이트를 찾는 플러터 개발자

고려 사항

  • 코드 생성 설정이 필요합니다
  • 기본 데이터베이스로 SQLite만 사용 가능
  • 복잡한 조인 또는 원시 SQL에 대한 내장 지원 없음
  • 마이그레이션 처리는 신중한 계획이 필요합니다
  • 대규모 서버 측 데이터베이스에 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Floor

See the project's website for the full documentation.

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.

pub package build status codecov

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.
dependencies:
  flutter:
    sdk: flutter
  floor: ^1.4.2

dev_dependencies:
  floor_generator: ^1.4.2
  build_runner: ^2.1.2
2. Create an Entity

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.

// entity/person.dart

import 'package:floor/floor.dart';

@entity
class Person {
  @primaryKey
  final int id;

  final String name;

  Person(this.id, this.name);
}
3. Create a DAO (Data Access Object)

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.dart

import 'package:floor/floor.dart';

@dao
abstract class PersonDao {
  @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);

  @insert
  Future<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 imports
import '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])
abstract class AppDatabase extends FloorDatabase {
  PersonDao get 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.

Bugs, Ideas, and Feedback

For bugs please use GitHub Issues. For questions, ideas, and discussions use GitHub Discussions.

License

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.

카테고리

의존성

의존성 목록 9 개

소스 저장소

이 패키지를 사용하는 프로젝트