123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- import 'package:sqflite/sqflite.dart';
- import 'dart:async';
- import 'dart:io';
- import 'package:path_provider/path_provider.dart';
- class SearchData {
- static SearchData _databaseHelper;
- static Database _database;
- final String tableSearch = 'TableSearch';
- final String columnId = 'id';
- final String title = 'title';
- SearchData._creatInstance();
- factory SearchData() {
- if (_databaseHelper == null) {
- _databaseHelper = SearchData._creatInstance();
- }
- return _databaseHelper;
- }
- Future<Database> initializeDatabase() async {
- Directory directory = await getApplicationDocumentsDirectory();
- String path = directory.path + 'search.db';
- var employeeDatabase =
- await openDatabase(path, version: 1, onCreate: _creatDB);
- return employeeDatabase;
- }
- void _creatDB(Database db, int newVersion) async {
- await db.execute(
- 'CREATE TABLE $tableSearch($columnId INTEGER PRIMARY KEY AUTOINCREMENT, $title TEXT)',
- );
- }
- Future<Database> get database async {
- if (_database == null) {
- _database = await initializeDatabase();
- }
- return _database;
- }
- Future<List<SearchModel>> getSearchList() async {
- Database db = await this.database;
- var result =
- await db.rawQuery("SELECT * FROM $tableSearch order by $columnId ASC");
- if (result == null || result.length == 0) {
- return null;
- }
- List<SearchModel> titles = List<SearchModel>();
- result.forEach((item) => titles.add(SearchModel.fromJson(item)));
- return titles.take(20).toList();
- }
- // Insert
- Future<int> insertSearch(SearchModel searchModel) async {
- Database db = await this.database;
- final searchList = await getSearchList();
- if (searchList != null &&
- searchList
- .where((element) => element.title == searchModel.title)
- .length >
- 0) {
- return 0;
- } else {
- var result = await db.insert(tableSearch, searchModel.toJson());
- return result;
- }
- }
- // Delete
- Future<int> deleteSearch(String titleSearch) async {
- var db = await this.database;
- int result = await db
- .rawDelete("DELETE FROM $tableSearch WHERE $title = '$titleSearch'");
- return result;
- }
- Future<int> deleteSearchList() async {
- var db = await this.database;
- int result = await db.rawDelete("DELETE FROM $tableSearch");
- return result;
- }
- }
- class SearchModel {
- int id;
- String title;
- SearchModel({this.id, this.title});
- SearchModel.fromJson(Map<String, dynamic> json) {
- id = json['id'];
- title = json['title'];
- }
- Map<String, dynamic> toJson() {
- final Map<String, dynamic> data = new Map<String, dynamic>();
- data['id'] = this.id;
- data['title'] = this.title;
- return data;
- }
- SearchModel.fromSql(Map<String, dynamic> json) {
- id = json['id'];
- title = json['title'];
- }
- }
|