nui_database 1.1.2
nui_database: ^1.1.2 copied to clipboard
A new Flutter package.
id: flutter-sdk-nuidatabase title: NUIDatabase Overview sidebar_label: Overview #
NUIDatabase is part of the Flutter SDK that allows you to integrate local database feature into the app in a more convenient and simpler way:
-
Simplified Database Initialization - Specify all the entities that are going to be in database, the name of the database and you are good to go.
-
Entity Based - Add any entity/table to the database as long as it extends
NUIDBEntity. These entities will be json decodable/encodable by default. -
Multiple Database In A Single App - Initialize multiple databases with
NUIDatabaseBuilderand access any of the databases from theNUIDatabaseinstance with the targeted database name. -
Migration Made Easy - All the entity migrations are done automatically, let it be adding a new entity, removing a new entity, adding new fields or removing fields.
NUIDatabaseautomatically detects the changes in the database structure and migrate the database whenever neccessary.
Builder Method for NUIDatabase #
| Method | Remark |
|---|---|
model() |
Specify the database model that extends NUIDatabaseModel |
readyCallback() |
Add a callback to know when the database is opened and ready |
build() |
Build the NUIDatabase instance with the builder. |
Initialize NUIDatabase with NUIDatabaseBuilder. #
Create a NUIDatabaseBuilder instance to build the NUIDatabase instance.
var builder = NUIDatabaseBuilder();
Specifying the database model for NUIDatabase. #
On the builder method, users are required to specify the database model, which must extends NUIDatabaseModel and provide the name and entities for this database.
class XPloreDatabase extends NUIDatabaseModel{
static const String name = "xplore.db";
static NUIDatabase get(){
return NUIDatabase.get(name);
}
String databaseName() => name;
List<NUIDBEntityMapper> entities() => [
AppUserEntity(),
CommentEntity(),
PlaceEntity(),
SettingEntity(),
NUIMediaFileEntity(),
NotificationEntity(),
TravelRecordEntity(),
DailyTrackerEntity(),
PostEntity(),
EventEntity()
];
}
builder.model(XPloreDatabase());
Adding a Callback To The Builder. #
On the builder method, users can add a callback listener to be notified when the database is opened and ready to be used.
builder.readyCallback((success, message){
log("Open database successful : $success");
});
Build the NUIDatabase instance #
Once all the configurations are done for the NUIDatabaseBuilder, building the instance will return the instance of the NUIDatabase.
Future<NUIDatabase> db = builder.build();
A Complete Example for Building A NUIDatabase Instance #
final db = NUIDatabaseBuilder()
.model(XPloreDatabase())
.readyCallback((success, message) {
log("Open database with success : $success");
})
.build();
Available Methods for NUIDatabase #
| Method | Remark |
|---|---|
get() |
Get the instance of the built NUIDatabase instance |
getOne() |
Get a single item from the database |
getList() |
Get a list of items from the database with optional filters |
save() |
Save an item into the database |
saveList() |
Save a list of items into the database |
update() |
Update an item in the database |
updatePartial() |
Update specific fields of an item into the database |
delete() |
Delete an item from the database |
clear() |
Remove all the items in an entity/table |
Getting the NUIDatabase Instance #
Users can get the NUIDatabase instance for the any specific database as long as it is build previously with NUIDatabaseBuilder.
final db = NUIDatabase.get("xplore.db");
Defining an Entity #
To register an entity to the NUIDatabase, simply create a class that extends NUIDBEntity and implement the abstract methods. Each entity class comes with its individual NUIDBEntityMapper class that represents the identity of this entity. It defines all the fields available for this entity.
class TravelRecord extends NUIDBEntity<TravelRecord>{
TravelRecord();
TravelRecord.empty();
String areacodeLine;
String lastVisitedDate;
int lastVisitedDateLong;
int stayDuration;
String countryCode;
bool isBought = false;
@override
NUIEntMapper<TravelRecord> mapper() => TravelRecordEntity();
}
class TravelRecordEntity extends NUIDBEntityMapper<TravelRecord>{
@override
List<NUIDBField> dbFields() {
final fields = [
NUIDBField<TravelRecord>(name: "areacodeLine", type: NUIEntType.STRING, setter: (data, value) => data.areacodeLine = value, getter: (data) => data.areacodeLine, primaryKey: true),
NUIDBField<TravelRecord>(name: "lastVisitedDate", type: NUIEntType.STRING, setter: (data, value) => data.lastVisitedDate = value, getter: (data) => data.lastVisitedDate),
NUIDBField<TravelRecord>(name: "lastVisitedDateLong", type: NUIEntType.INTEGER, setter: (data, value) => data.lastVisitedDateLong = value, getter: (data) => data.lastVisitedDateLong),
NUIDBField<TravelRecord>(name: "stayDuration", type: NUIEntType.INTEGER, setter: (data, value) => data.stayDuration = value, getter: (data) => data.stayDuration),
NUIDBField<TravelRecord>(name: "countryCode", type: NUIEntType.INTEGER, setter: (data, value) => data.countryCode = value, getter: (data) => data.countryCode),
NUIDBField<TravelRecord>(name: "isBought", type: NUIEntType.BOOLEAN, setter: (data, value) => data.isBought = value, getter: (data) => data.isBought),
];
return fields;
}
@override
String entityName() => "TravelRecord";
@override
TravelRecord newInstance() => TravelRecord.empty();
}
Declaring Non-Primative Field Types #
Most of the time we will need to store objects or list of objects within an entity, NUIDBEntity allows non-primitive fields to be declared in the entity.
final listObjectField = NUIDBField<T>(name: "images", type: NUIEntType.LIST_OBJECT, setter: (data, value) => data.images = asListOfDBObjects(NUIMediaFileEntity(), value), getter: (data) => data.images),
final objectField = NUIDBField<T>(name: "image", type: NUIEntType.OBJECT, setter: (data, value) => data.image = asDBObject(NUIMediaFileEntity(), value), getter: (data) => data.image),
final listStringField = NUIDBField<T>(name: "hashtags", type: NUIEntType.LIST_STRING, setter: (data, value) => data.hashTags = asList<String>(value), getter: (data) => data.hashTags),
Get a Single Item #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityMapperN The entity mapper for this for the entity conditionInnerLevelQueryY The filtering conditions for the query groupByStringY Group the query by this field orderByStringY The field for the query sorting orderNUIQueryOrderY Order the field by either ascending or descending offsetintY Offset the query callbackDBQueryCallbackY Add a callback to listen to the query result
Example of Getting a Single Item #
final tracker = await NUIDatabase.get("xplore.db").getOne(DailyTrackerEntity(), condition: (condition){
return condition.where(field: "date", condition: NUIDBQueryType.EQUALS, value: "20200912");
});
Get a List of Items #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityMapperN The entity mapper for this for the entity conditionInnerLevelQueryY The filtering conditions for the query groupByStringY Group the query by this field orderByStringY The field for the query sorting orderNUIQueryOrderY Order the field by either ascending or descending offsetintY Offset the query callbackDBQueryCallbackY Add a callback to listen to the query result limitintY Limit the number of items returned from the query
Example of Getting a List of Items #
final lastTravelAreas = await NUIDatabase.get("xplore.db").getList(TravelRecordEntity(), orderBy: Parameters.FIELD_MODIFIED_AT, order: NUIQueryOrder.DESC, limit: 8);
Save an Item #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityN The entity data to be saved callbackDBExecuteCallbackY A callback to be notified when the save is completed recordDateboolY To save the last saved date for this entity, default is set to true
Example of Saving an Item #
await NUIDatabase.get("xplore.db").save(data);
Save a List of Items #
- Parameters:
Name Type Nullable Remark entitiesList<NUIDBEntity>N The list of entities to be saved callbackDBExecuteCallbackY A callback to be notified when the save is completed recordDateboolY To save the last saved date for this entity, default is set to false
Example of Save a List of Items #
await NUIDatabase.get("xplore.db").saveList(items, recordDate: true);
Update an Item #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityN The entity data to be updated callbackDBExecuteCallbackY A callback to be notified when the update is completed conditionInnerLevelQueryY The filtering conditions for the update query
Example of Updating an Item #
await NUIDatabase.get("xplore.db").update(TravelRecord(), condition: (query){
return query.where(field: "date", type: NUIEntType.DATE, condition: NUIDBQueryType.EQUALS, value: "20200102");
});
Update an Item by Specific Fields #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityMapperN The entity mapper of the data to be updated updatesMap<String, dynamicN The map of values to be updated callbackDBExecuteCallbackY A callback to be notified when the update is completed conditionInnerLevelQueryY The filtering conditions for the update query
Example of Updating an Item by Specific Fields #
await NUIDatabase.get("xplore.db").updatePartial(TravelRecordEntity(), {
"address": "The new address",
"date" : "20201014"
}, condition : (query){
return query.where(field: "date", type: NUIEntType.DATE, condition: NUIDBQueryType.EQUALS, value: "20200102");
});
Delete an Item #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityMapperN The entity mapper of the data to be deleted callbackDBExecuteCallbackY A callback to be notified when the delete is completed conditionInnerLevelQueryY The filtering conditions for the delete query
Example of Deleting an Item #
await NUIDatabase.get("xplore.db").delete(TravelRecordEntity(), condition : (query){
return query.where(field: "date", type: NUIEntType.DATE, condition: NUIDBQueryType.EQUALS, value: "20200102");
});
Clear All Items From an Entity #
- Parameters:
Name Type Nullable Remark entityNUIDBEntityMapperN The entity mapper of the data to be cleared callbackDBExecuteCallbackY A callback to be notified when the clear is completed
Example of Clearing All Items From an Entity #
await NUIDatabase.get("xplore.db").clear(TravelRecordEntity());