I am working with an already existing database dictionary.db that has a table words and has 4 columns id, englishWord, germanWord, isFavorite.
Using Sqflite I am trying to return a list of German words based on an input in English pretty much the userflow works like this: user input an English word (example: "Ability") and I return a list of synonyms to that word in German.
My problem is I don't know how to do it the method I am trying returns the full list instead of only the intended search results
This is my Entity:
class Word {
final String id;
final String eng;
final String ger;
final String isFav;
Word({this.id, this.eng, this.ger, this.isFav});
Map<String, dynamic> toMap() {
return {
'wordId': id,
'englishWord': eng,
'germanWord': ger,
'isFavorite': isFav,
};
}
factory Word.fromMap(Map<String, dynamic> json) => new Word(
id: json['wordId'],
eng: json['englishWord'],
ger: json['germanWord'],
isFav: json['isFavorite']
);
}
And this is my database helper class:
class DatabaseHelper{
DatabaseHelper._();
static final DatabaseHelper databaseHelper = DatabaseHelper._();
Database _database;
static const String DB_NAME = "dict.db";
static const String TABLE = "words";
static const String ID = "wordId";
static const String ENGLISH_WORD = "englishWord";
static const String GERMAN_WORD = "germanWord";
static const String IS_FAV = "isFavorite";
Future<Database> get database async {
if (_database != null) return _database;
_database = await getDatabaseInstance();
return _database;
}
Future<Database> getDatabaseInstance() async {
io.Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, DB_NAME);
return await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE IF NOT EXISTS $TABLE ("
"$ID TEXT,"
"$ENGLISH_WORD TEXT,"
"$GERMAN_WORD TEXT,"
"$IS_FAV TEXT"
")");
});
}
//This is where I get the search result list
//I am stuck here I don't know where to go from here, I only get the full list
Future<List<Word>> searchEnglishResults(String userSearch) async{
final db = await database;
var response = await db.query("Word");
List<Word> list = response.map((c) => Word.fromMap(c)).toList();
return list;
}
I assumed the database is like below:
|id | englidhWord | germanWord | isFavorite |
|-------|-------------|-------------------|------------|
| 'id0' | 'bye' | 'Tschüss' | 'false' |
| 'id1' | 'bye' | 'Auf Wiedersehen' | 'true' |
so if the user searches for "bye", she/he should receive [ 'Tschüss', 'Auf Wiedersehen'](the Word model not only the German words).
For that, query has some options like where and whereArgs that you can use to search for a specific row on the database.
Here we want to search the database for rows that their englidhWord field has a value of bye.
Here is the edited version of your DB:
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sudoku/src/word.dart';
class DatabaseHelper {
DatabaseHelper._();
static final DatabaseHelper databaseHelper = DatabaseHelper._();
Database _database;
String DB_NAME = "dict.db";
static const String TABLE = "words";
static const String ID = "wordId";
static const String ENGLISH_WORD = "englishWord";
static const String GERMAN_WORD = "germanWord";
static const String IS_FAV = "isFavorite";
Future<Database> get database async {
if (_database != null) return _database;
_database = await getDatabaseInstance();
return _database;
}
Future<Database> getDatabaseInstance() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, DB_NAME);
return await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE IF NOT EXISTS $TABLE ("
"$ID TEXT,"
"$ENGLISH_WORD TEXT,"
"$GERMAN_WORD TEXT,"
"$IS_FAV TEXT"
")");
});
}
//add new words
Future<int> add(Word word) async {
final db = await database;
var response = await db.insert(TABLE, word.toMap());
return response;
}
//This is where I get the search result list
//I am stuck here I don't know where to go from here, I only get the full list
Future<List<Word>> searchEnglishResults(String userSearch) async {
final db = await database;
var response = await db
.query(TABLE, where: '$ENGLISH_WORD = ?', whereArgs: [userSearch]);
List<Word> list = response.map((c) => Word.fromMap(c)).toList();
return list;
}
}
And I show the result with listview on a page named MyApp
import 'package:flutter/material.dart';
import 'package:sudoku/src/db.dart';
import 'package:sudoku/src/word.dart';
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
DatabaseHelper db;
#override
void initState() {
db = DatabaseHelper.databaseHelper;
add();
super.initState();
}
add() async {
// await db.add(Word(eng: 'hi', ger: 'Hallo', id: 'id2', isFav: 'true'));
// await db.add(Word(eng: 'bye', ger: 'Tschüss', id: 'id0', isFav: 'fasle'));
// await db.add(
// Word(eng: 'bye', ger: 'Auf Wiedersehen', id: 'id0', isFav: 'true'));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: FutureBuilder<List<Word>>(
future: db.searchEnglishResults('bye'),
builder: (BuildContext context, AsyncSnapshot<List<Word>> snapshot) {
if (snapshot.hasData)
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(snapshot.data[index].ger),
subtitle: Text(snapshot.data[index].eng),
trailing: Text(snapshot.data[index].isFav),
);
},
itemCount: snapshot.data.length,
);
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
I included a function named "add" in database and MyApp's initState to add new words to database.
If you refresh app for multiple time, it will add repetitive rows, the reason is that you should make one of the DB field unique, here can be id to do so you should create the table like below:
return await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE IF NOT EXISTS $TABLE ("
"$ID TEXT NOT NULL PRIMARY KEY,"
"$ENGLISH_WORD TEXT,"
"$GERMAN_WORD TEXT,"
"$IS_FAV TEXT"
")");
});
Also in add function in DB, you should choose what should be done when it faces to a repetitive row(Word here), there are some options, one can be to replace it, it should change like this:
//add new words
Future<int> add(Word word) async {
final db = await database;
var response = await db.insert(TABLE, word.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
return response;
}
I hope it was what You were looking for.
Related
I new in Flutter.
I have already exist db and need add it to app.
Put file in assets/db/sms.db
in file pubspec.yaml
assets:
- assets/db/sms.db
Copy db file in applicationDirectory.
In file categoriesList.dart I try connect to it.
SmsDataBaseHelper.instance.getAllCategories()
I get error message.
database_helper.dart
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'dart:io' as io;
import '/models/categories.dart';
class SmsDataBaseHelper {
static final SmsDataBaseHelper instance = SmsDataBaseHelper._();
static Database? _db;
SmsDataBaseHelper._();
Future<Database> get db async {
_db ??= await _init();
return _db!;
}
Future<Database> _init() async {
io.Directory applicationDirectory = await getApplicationDocumentsDirectory();
String dbPathSms = path.join(applicationDirectory.path, "sms.db");
bool dbExistsSms = await io.File(dbPathSms).exists();
if (!dbExistsSms) {
// Copy from asset
ByteData data = await rootBundle.load(path.join("assets", "db", "sms.db"));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await io.File(dbPathSms).writeAsBytes(bytes, flush: true);
}
return await openDatabase(dbPathSms);
}
/// get all the words from categories
Future<List<Categories>> getAllCategories() async {
if (_db == null) {
throw "_db is not initiated, initiate using [init(db)] function";
}
List<Map>? categories;
await _db!.transaction((txn) async {
categories = await txn.query(
"categories",
columns: [
"name",
"ru",
],
);
});
return categories!.map((e) => Categories.fromJson(e as Map<String, dynamic>)).toList();
}
}
categoriesList.dart
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import '../utils/database_helper.dart';
import '../models/categories.dart';
class CategoriesList extends StatefulWidget {
const CategoriesList({super.key});
#override
State<CategoriesList> createState() => _CategoriesListState();
}
class _CategoriesListState extends State<CategoriesList> {
//late List<Categories> categoriesList;
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SMS Home Page'),
),
body: FutureBuilder<List<Categories>>(
future: SmsDataBaseHelper.instance.getAllCategories(),
builder: (BuildContext context, AsyncSnapshot<List<Categories>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const Text('start widget');
case ConnectionState.active:
case ConnectionState.waiting:
return const Text('Awaiting result from api...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return Text('Result: ${snapshot.data}');
}
},
),
);
}
}
use this class to build database ..
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class SqlDb {
static Database? _db;
Future<Database?> get db async {
if (_db == null) {
_db = await initialDb();
return _db;
} else {
return _db;
}
}
initialDb() async {
String databasepath = await getDatabasesPath();
String path = join(databasepath, 'shop.db');
Database mydb = await openDatabase(path,
onCreate: _onCreate, version: 1, onUpgrade: _onUpgrade);
return mydb;
}
_onUpgrade(Database db, int oldversion, int newversion) async {}
deletemydatabase() async {
String databasepath = await getDatabasesPath();
String path = join(databasepath, 'shop.db');
var x = await deleteDatabase(path);
return x;
}
_onCreate(Database db, int version) async {
await db.execute(
"CREATE TABLE cart (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , title TEXT, size TEXT , code TEXT , img TEXT , price TEXT )");
}
//Select
readData(String sql) async {
Database? mydb = await db;
List<Map> response = await mydb!.rawQuery(sql);
return response;
}
//insert data
insertData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawInsert(sql);
return response;
}
deleteData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawDelete(sql);
return response;
}
updateData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawUpdate(sql);
return response;
}
}
I wanna create db with sqflite but this no create and show something issue, Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "no such table: todo" UserInfo={NSLocalizedDescription=no such table: todo}) sql 'SELECT * FROM todo WHERE id = ?' args [11], oke let's check it my db helper :
db helper
import 'package:sqflite/sqflite.dart';
import 'model.dart';
class DatabaseHelper {
//singleton base
static DatabaseHelper? _instance;
DatabaseHelper._internal() {
_instance = this;
}
factory DatabaseHelper() => _instance ??= DatabaseHelper._internal();
//TODO: add database name
static late Database _database;
//TODO: add get database
Future<Database> get databse async {
_database = await _initializeDatabase();
return _database;
}
//TODO: add db name
static String _tableName = 'todo';
//TODO: initialize db
Future<Database> _initializeDatabase() async {
final path = await getDatabasesPath();
final db = openDatabase('notes.db', version: 1, onCreate: (db, version) {
version:
1;
db.execute('''CREATE TABLE $_tableName(
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT,
)''');
});
return db;
}
Future<void> insertData(Note note) async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(
_tableName,
where: 'id = ?',
whereArgs: [note.id],
);
await db.insert(_tableName, note.toJson());
}
//get
Future<List<Note>> getAllNotes() async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(_tableName);
return result.map((e) => Note.fromJson(e)).toList();
}
}
I need help :(
I'm trying to delete Data from a Sqflite Database.
I can insert and get the data to show, but I cannot delete it if I do a mistake in saving it.
I have my DB:
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sqflite.dart';
//SQFLITE
class DBHelper {
static Future<sql.Database> database() async {
final dbPath = await sql.getDatabasesPath();
//einmal die Datenbank erstellen in einer Variablen
return sql.openDatabase(path.join(dbPath, 'wanderwege.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE user_places(id TEXT PRIMARY KEY, title TEXT, image TEXT, createTime TEXT, place TEXT, description TEXT)');
// 'CREATE TABLE user_places(id TEXT PRIMARY KEY, title TEXT, image TEXT, loc_lat REAL, loc_lng REAL, address TEXT)');
}, version: 1);
}
//Da der Eintrag dauern kann bis es in die Daten gespeichert weerden = Future + async
static Future<void> insert(String table, Map<String, Object> data) async {
final db = await DBHelper.database();
db.insert(table, data, conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
// Delete data from table
// deleteData(table, itemId) async {
// final db = await DBHelper.database();
// return await db.rawDelete("DELETE FROM $table WHERE id = $itemId");
// }
//Methode um Einträge zu holen
static Future<List<Map<String, dynamic>>> getData(String table) async {
final db = await DBHelper.database();
return db.query(table);
}
}
Then I have my Places:
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:places/helpers/db_helper.dart';
import 'package:places/models/place.dart';
import 'package:intl/intl.dart';
class GreatPlaces with ChangeNotifier {
//To set Creation Time
static DateTime actualTime = DateTime.now();
String formattedDate = DateFormat('dd-MM-yyyy').format(actualTime);
List<Place> _items = [];
List<Place> get items {
return [..._items];
}
//Information des gesamten places
Place findById(String id) {
return items.firstWhere((place) => place.id == id);
}
Future<void> addPlace(
String pickedTitle,
File pickedImage,
String pickedDate,
String pickedLocation,
String pickedDescription,
//PlaceLocation pickedLocation,
) async {
//final address = await LocationHelper.getPlaceAddress(
// pickedLocation.latitude, pickedLocation.longitude);
// final updatedLocation = PlaceLocation(
// latitude: pickedLocation.latitude,
// longitude: pickedLocation.longitude,
// address: address);
final newPlace = Place(
id: DateTime.now().toString(),
image: pickedImage,
title: pickedTitle,
createTime: pickedDate,
place: pickedLocation,
description: pickedDescription,
);
//location: null);
_items.add(newPlace);
notifyListeners();
//übergabe 'wanderwege' so wie in db_helper definiert , Data ist von typ map
DBHelper.insert('user_places', {
'id': newPlace.id,
'title': newPlace.title,
'image': newPlace.image.path,
'createTime': newPlace.createTime,
'place': newPlace.place,
'description': newPlace.description
// 'loc_lat': newPlace.location.latitude,
// 'loc_lng': newPlace.location.longitude,
// 'address': newPlace.location.address,
});
}
//Die ganzen places aus der DB holen
Future<void> fetchAndSetPlaces() async {
final dataList = await DBHelper.getData('user_places');
_items = dataList
.map((item) => Place(
id: item['id'],
title: item['title'],
image: File(item['image']),
createTime: item['createTime'],
place: item['place'],
description: item['description'],
//location: null // latitude: item['loc_lat'],
// longitude: item['loc_lat'],
// address: item['address']),
))
.toList();
notifyListeners();
}
}
and now on the screen where all the Places listed I want to implement a delete function, but I don't get how it works... tried so much from youtube and the documentation from Sqflite, but I don't get it.
I hope someone can help me.
Greetings :)
I've made this simple helper file (like you have done) for a little app that uses sqflite as backend in local. It's complete: it accesses to the local file system to get grant permissions, it opens the file for write , and you can make also Batch updates:
import 'dart:async';
import 'package:sqflite/sqflite.dart';
class DBClient {
final logger = Log.getLogger('\u{1F5AB} DBClient '); // a little logger utility, you can substitute with the simple 'print(...)' function.
static final String dbFilename = 'my_database.db';
final Permission permission;
Database _database;
bool openingDB = false;
DBClient(this.permission) : assert(permission != null);
Batch batch() {
return _database.batch();
}
Future<void> init() async {
if (_database == null && !openingDB) {
String path;
try {
path = await permission.getAbsoluteFileName(dbFilename);
} on Error {
logger.e('Error: cannot open db');
rethrow;
}
openingDB = true;
logger.d('Opening database on path: $path');
_database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute("""
CREATE TABLE IF NOT EXISTS ......
""");
await db.execute("""
CREATE TABLE IF NOT EXISTS ....
""");
....
await db.execute("""
CREATE TABLE IF NOT EXISTS ....
""");
});
}
}
Future<int> insert(String tableName, Map<String, dynamic> json) async =>
_database.insert(tableName, json);
Future<List<Map<String, dynamic>>> query(
String tableName, {
String where,
List<dynamic> whereArgs,
}) async {
return _database.query(
tableName,
where: where,
whereArgs: whereArgs,
);
}
Future<int> update(String tableName, Map<String, dynamic> json,
{String where, List<dynamic> whereArgs}) async {
return _database.update(
tableName,
json,
where: where,
whereArgs: whereArgs,
);
}
Future<int> delete(String tableName,
{String where, List<dynamic> whereArgs}) async {
return _database.delete(
tableName,
where: where,
whereArgs: whereArgs,
);
}
}
You can use in this manner:
deleted = await db.delete(Place.tableName(),
where: "name = ?", whereArgs: [name]);
Hint: in the init() method you can use AsyncMemoizer class, it is better to grant that the method is called only once (at the time I wrote the app I didn't do it....)
Hereafter my (very old) dependencies:
dependencies:
date_utils: ^0.1.0+3
equatable: ^1.1.1
logger: ^0.8.3
permission_handler: ^5.0.0+hotfix.3
quiver: ^2.1.3
sqflite: ^1.3.0
path_provider: ^1.6.5
flutter:
sdk: flutter
String q = "DELETE FROM Test WHERE id= '$id'";
Just use this:
await db.rawDelete('DELETE FROM $table WHERE id = ?',[itemId],);
Just use this function with parameter as id
Future<int> delete(int id) async {
return await db.delete(tableName, where: '$columnId = ?', whereArgs: [id]);}
I am trying to get an async function _read() to run and the function does not pass the line:
Reading reading = await helper.queryReading(rowId); in this function:
_read() async {
DatabaseHelper helper = DatabaseHelper.instance;
int rowId = 1;
//lines above here executes
Reading reading = await helper.queryReading(rowId); //this is the line it stops on
// nothing below here is executed
if (reading == null) {
print('read row $rowId: empty');
} else {
print('read row $rowId: ${reading.reading}');
}
}
It is being called from the following function
class Profile {
Widget getScreen(){
print("Attempting to read db");
_read();
return Scaffold( ...)
Here is my helper class:
import 'dart:ffi';
import 'dart:io';
import 'package:ema/Readings.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
//table structure
final String tableName = 'Readings';
final String databasecolumnId = '_id';
final String databaseReading = 'Reading';
final String databaseDate = 'Time';
class DatabaseHelper {
//This is the name of the database file on disk
static final _databaseName = "readings.db";
//handles versioning for databases
static final _databaseVersion = 1;
//makes a singleton classs
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
//allows only one item to access the database
static Database _database;
Future<Database> get database async {
_database = await _initDatabase();
return database;
}
//this opens and creates the database
_initDatabase() async {
// The path_provider plugin gets the right directory for Android or iOS.
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
// Open the database. Can also add an onUpdate callback parameter.
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
//Creates the database
Future _onCreate(Database db, int version) async {
await db.execute(
'''
CREATE TABLE $tableName (
$databasecolumnId INTEGER PRIMARY KEY,
$databaseReading REAL NOT NULL,
$databaseDate INTERGER NOT NULL
)
'''
);
}
Future<int> insertReading(Reading reading) async {
Database db = await database;
int id = await db.insert(tableName, reading.toMap());
return id;
}
//gets reading
Future<Reading> queryReading(int id) async {
print("queryReading"); //gets here
Database db = await database;
print("Getting Db"); // not actually getting here
List<Map> maps = await db.query(tableName,
columns: [databasecolumnId, databaseReading, databaseDate],
where: '$databasecolumnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Reading.fromMap(maps.first);
}
print('maps length : ${maps.length}');
return null;
}
}
Here is my Readings class:
class Reading {
int id;
double reading;
DateTime date;
//constructor
Reading({this.id, this.reading, this.date});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
databaseReading: reading,
databaseDate: date.millisecondsSinceEpoch,
};
if (id != null) {
map[databasecolumnId] = id;
}
return map;
}
//extracts a node object from the map obect
Reading.fromMap(Map<String, dynamic> map) {
id = map[databasecolumnId];
reading = map[databaseReading];
date = new DateTime.fromMillisecondsSinceEpoch(map [databaseDate]);
}
}
Turns out there was a deadlock in getting the database. By putting a lock on it it worked.
Here is the code to resolve it:
///declreation of the database
Database _database;
///Gets the database ensuring that there are no locks currently on the database
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
So basically what i want to do is:
When the user turns on the app for the first time,
The SQLite database is created and the data is fetched from the internet.
Until this is done, SetupPage() widget is displayed in scaffolds body or else Home() is displayed.
Now the code i wrote works perfectly for the first time, but when i open it the second time,
The SetupPage() only shows, it never goes back to the Home(). What am i doing wrong here ?
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:path/path.dart';
import 'pages/home.dart';
import 'pages/SetUpPage.dart';
import 'package:sqflite/sqflite.dart';
class App extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<App> {
final bgColor = const Color(0xFF1abc9c);
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
bool status = false;
Database database;
#override
void initState() {
initializeData();
super.initState();
}
void initializeData() async
{
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
status = false;
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE news (id INTEGER PRIMARY KEY, topic TEXT, img TEXT, newstitle TEXT, news TEXT, newslink TEXT)');
fetchData();
}
);
database.close();
}
#override
Widget build(context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("UnFound News"),
backgroundColor: bgColor,
),
body: status ? Home() : SetUpPage(),
);
}
/*Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);*/
void fetchData() async {
var result = await get("https://api.myjson.com/bins/a0bvu");
var arr = json.decode(result.body)['post'];
for(int i = 0; i < arr.length; i++)
{
//TODO: Implement addition to database.
}
setState(() {
status = true;
});
}
}
You probably want to put the fetchData in a onOpen parameter instead of the onCreate parameter like this:
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE news (id INTEGER PRIMARY KEY, topic TEXT, img TEXT, newstitle TEXT, news TEXT, newslink TEXT)');
await fetchData();
}, onOpen: (Database db) async {
setState(() {
status = true;
});
});
static Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
//Creating a database with name test.dn in your directory
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "test.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
checkDb(){
//do operation
var dbClient = await db;
}