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

패키지 상세v6.1.0

dbutils

SQLite 및 향후 구현될 수 있는 다른 DBMS의 수에 관계없이 사용할 수 있는 데이터베이스 유틸리티 클래스 라이브러리입니다.

AndroidiOSmacOS
30일 다운로드
194
좋아요
8
Pub 점수
140

패키지 설치

flutter pub add dbutils

패키지 개요

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

dbutils는 SQLite 및 미래의 데이터베이스 관리 시스템과 함께 작업하기 위한 통합 유틸리티 라이브러리를 제공하는 Flutter/Dart 패키지입니다. 다양한 플랫폼에서 일관된 인터페이스를 제공하여 데이터베이스 작업을 간소화하며, 개발자가 연결을 관리하고 쿼리를 실행하며 트랜잭션을 효율적으로 처리할 수 있도록 합니다. 확장성을 고려해 설계되어 Android, iOS, macOS를 지원하며, 신뢰할 수 있는 데이터 지속성 요구가 있는 크로스플랫폼 앱에 적합합니다. 저수준 데이터베이스 상호작용을 추상화하여 반복 코드를 줄이고 유지보수성을 향상시킵니다.

사용 사례

  • 크로스 플랫폼 앱 데이터 저장
  • SQLite 작업 간소화
  • 추가 DBMS를 위한 미래 대비
  • 데이터베이스 연결 관리 간소화
  • 반복적인 데이터베이스 코드 줄이기
  • 트랜잭션 처리 활성화

주요 기능

  • SQLite 및 미래 DBMS를 위한 통합 인터페이스
  • Android, iOS 및 macOS 지원
  • 새 데이터베이스를 위한 확장 가능한 아키텍처
  • 내장형 연결 풀링
  • 거래 지원
  • 최소한의 보일러플레이트

적합한 대상

  • 지속적인 데이터 저장이 필요한 플러터 개발자
  • 다중 데이터베이스 호환성이 필요한 앱
  • 코드 유지보수를 우선시하는 팀
  • 다수의 모바일 및 데스크톱 플랫폼을 대상으로 하는 프로젝트
  • 원시 SQL에 대한 추상화를 찾는 개발자

고려 사항

  • 현재는 SQLite에 한정되어 있습니다(미래의 DBMS는 아직 구현되지 않았습니다)
  • 기본적인 SQL 이해가 필요합니다
  • 복잡한 쿼리에 대해 추가 설정이 필요할 수 있습니다
  • 완전한 ORM는 아니며, 단지 유틸리티만 제공
  • 외부 데이터베이스 드라이버에 의존합니다
  • 중간에서 대규모 데이터베이스 사용 사례에 가장 적합

원본 README

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

SQLite in Flutter

Demonstrating the Dart package, dbutils. Medium Pub.dev GitHub stars

The Dart package, dbutils, was written to work with the SQLite plugin, sqflite, which was written by Alex Tekartik. The plugin knows how to ‘talk to’ a SQLite database, while the Dart package knows how to ‘talk to’ the plugin. The end result allows you to manipulate the SQLite database that much easier. Before continuing, I would suggest installing the Dart package now as it includes the very same example app demonstrated here in this article. Follow the three steps below, and you’re on your way to easily working with a SQLite database in your Flutter app.

sqlitedbutils

Installing

I don't always like the version number suggested in the 'Installing' page. Instead, always go up to the 'Major' value in the semantic version number when installing my library packages. This means always entering a version number with then two trailing zeros, '.0.0'. This allows you to take in any 'minor' versions introducing new features, or in this case, any 'patch' versions that involves bugfixes. Semantic version numbers are always in this format: major.minor.patch.

  1. patch - I've made bugfixes
  2. minor - I've introduced new features
  3. major - I've essentially made a new app. It's broken backwards-compatibility and has a completely new user experience. You won't get this version until you increment the major number in the pubspec.yaml file.

And so, in this case, add this to your package's pubspec.yaml file instead:

dependencies:
  dbutils:^5.0.0
What's on the Table?

In the example app, we have the class, Employee, that extends the class library called, DBInterface. It’s found in the Dart package and implements the three required properties: To getters called name and version and one function called onCreate(). The ‘name’ is the name of the database to contain all the tables you would then define in the function, onCreate(). The ‘version’ is of course the version number of the database. Pretty straightforward so far. employee So, in the screenshot above, you see what makes up the Dart file, Employee.dart. Looking inside the onCreate() function, you’ll realize it’s required you be comfortable with SQL as it’s used to create and manipulate the data tables. Listed at the end of the Employee class, are functions used to save any changes to an Employee record be it editing an existing record or creating an brand new one. There’s the function to delete an Employee record, as well as, a function to retrieve the Employee records from the SQLite database. The last function listed provides an ‘empty’ Employee record used typically when creating a brand new Employee record.

Keep It Single

Note, I’ve chosen to use a factory constructor for this Employee class. Doing so enforces the singleton pattern described in Item 1 of Joshua Bloch’s now famous 2001 book, Effective Java. Therefore, with each subsequent instantiation of this class, only ‘one instance’ of Employee is utilized. We don’t want more than one instance of the ‘Employee’ table running in this app.

In the screenshot below, you see the keyword, factory, allows for a return statement in the constructor. In this case, it returns the static property, _this, that will contain the one and only instance of the this class. factory

Once Is Enough

For example, going to the ‘Employee details’ screen where you view an employee’s information, you have the option to delete that record. As it’s not a common operation, there’s no need to define a memory variable to take a instantiated reference of the Employee class. Merely call the constructor. We know, by time we visit this screen, the Employee class has already been instantiated and will return that one instance. delete

Saved By One

Further on in that every same class there’s the function, _submit, called to save any changes made to the employee information. By the way, it’s also used to save brand new employee records. Note, it too calls the constructor, Employee(), to get that one instance to save that employee record. screen1

It's Opened and Closed

When you look at the sample app, you’ll see where the Employee table is first instantiated in the State object’s initState() function. In most cases, that’s the appropriate place to do that. In fact, with most Dart packages and class libraries, the common practice is to initialize and dispose of them in a State object’s initState() and dispose() functions respectively. And so, in most cases, the dbutils Dart package’s has an init() function that opens the database, and a disposed() function that closes the database. Note, however, in the screenshot below, the init() function call is commented out. screen1 It’s commented out to demonstrate the ability of the library class to open the database whenever there’s a query to be performed. This is the case with the getEmployees() function highlighted above. And so, in the screenshot below, deep in the class library, the rawQuery() function that’s eventually called will open the database if not open already. query

All Or Nothing

You can see in the getEmployees() function an SQL statement is executed to retrieve all the records that may be found in the table, Employee. It returns a List of Map objects—any and all the records found in the Employee table. The key of each Map object is, of course, a field name. Note, the class has a Map object, values, that takes in the last record in the table or an empty record if the table is also empty. getEmployee

Just For Show

Of course, we could have just as well removed the comment on that line and have the init() called in the initState() function. In fact, it would be better form to do so as it adds a little consistency to the code. You can see in the screenshot of the library below, the database is opened in the init() function. It’s then always appropriate call the functions disposed() or close() in the State object’s dispose() function to ensure the database is closed properly when terminating your app. screen1

Map It Out

The SQFlite plugin for Flutter, sqflite, deals with Map objects. This class library continues that approach and allows you to assign values to your table using Map objects. Below is a screenshot of the ‘Employee’ screen that displays an individual employee’s details. Note, a Map object, employee, is utilized to pass on the employee’s information to the TextFormField Widgets displayed and to take on any new values entered by the user. You can see where the Map object is used to also delete the Employee record it you wish. While, at the other end, the Map object is further used to save any new information to the data table. MyEmployee

Make the Save

In the sample app, you click in a button labelled, Save, to save the employee information. Looking at the code below, you see the save() function defined in the Employee class is called to perform the operation. As you’ve likely guessed by now, most operations involving the database are asynchronous and hence we’re working with Future objects. In this case, the save() function returns a Future object of type Boolean, Future, and we use the callback function, then(), to then notify the user if the save was successful as well as return to the previous screen. then

A Record Save

Inside the Employee class, the save() function, in turn, calls the saveRec() function. It passes the Map object containing the employee information as well as the name of the data table to be updated. save saveRec You can see the function, updateRec(), is called in turn to take the data deeper into the Dart package’s class library. We’re working with Future objects now. You can see below, we’re getting closer to the plugin itself calling an internal ‘helper’ class with its own updateRec() function. As you see, it’s enclosed in a try..catch statement. If there’s an error, another ‘helper’ class called _dbError will record the error and not crash the whole app. updateRec Finally, the internal class, _dbInt, has its updateRec() function perform the actual database operation. Notice, if the key field value is null, that implies this is a new Employee record and so the plugin, db, will call its insert() function to add this new record to the data table inside the database. Otherwise, it’s an existing record, and using the key field value to update the data table record. keyfield

Let's See Your Saves

When this example app starts up it’ll produce a list of employees entered so far. Below, is the code responsible to displaying that list. A query of the ‘Employee’ data table is performed with the use of a FutureBuilder widget, and when there’s data, the first and last name of each employee is listed out. EmployeeList displaying

Add Anew

Note the last little red arrow in the screenshot above. It reveals how an ‘empty’ Employee Map object is produced and passed to the ‘Employee’ screen so the user can enter a brand new employee.

To A Delete

As a counter, let’s walk through the process involved when deleting an Employee record. Let’s return to the ‘Employee’ screen that displays an individual employee, and note there is the ‘trash’ icon on the AppBar. You press that icon; you’ll call the Employee class’ deleteRec() function. Note, it passes that Map object containing the employee’s info. In particular, the key field id for that Employee record. screen1 In the deleteRec() function, the delete() function is called passing in the name of the data table as well as the key field value specified by the field name, id. Note, if no Map object was passed to the function, the class turns to its internal Map object, values, in the hope to provide the id value. deleteRec Further, in the dbutils class library, again the try..catch statement prevents the app from crashing all together if there’s an exception. Again, an internal helper class comes into play calling its own delete() function to perform the actual deletion. delete The final function returns a Future object of type int (the number of records deleted) upon a successful operation. It too requires the key field value to find the appropriate Employee record. Note, if the database is not open yet, it’s opened before the deletion is performed. delete

The Medium Article

Turn to the article, SQLite in Flutter, for more information: sqlite

Other Dart Packages

packages Other Dart packages from the author can also be found at Pub.dev

카테고리

의존성

의존성 목록 7 개

소스 저장소

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

아직 데이터가 없습니다.