I am following a tutorial about using Sqlite database in flutter from this link
SQFlite Database in flutter
but I get confused in some parts of this tutorial as following :
first what is the meaning of get db after Future. I don't understand the structure of function also when this function will execute? he doesn't call it in the tutorial ?
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
second in this function
he called method _onCreate but he doesn't pass any parameters
why and what does that mean ?
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;
}
Maybe this tutorial would be easier
tutorial
Anyway
Future<Database> get db - it's not field, it's just getter
So, when you call DBHelper.db - it checks _db if it isn't null and return Future with _db field.
Regarding onCreate: _onCreate
parameter onCreate in openDatabase method need 2 parameters (you can see this into sources)
typedef FutureOr OnDatabaseCreateFn(Database db, int version)
method _onCreate need the same parameters
void _onCreate(Database db, int version)
In such cases you can write onCreate: _onCreate - without parameters
I hope I've answered you questions. Write if something isn't clear
Related
I am using Flutter and using sqflite package, and I am trying to create a query to get an integer value from a database but it is giving me an error:
Here is the code:
Future<int> getCurrencyRate(String symb) async{
Database db = await instance.database;
return await db.rawQuery("Select rate from Currencies where symb= '$symb'");
}
It is showing this error:
A value of type 'List<Map<String, Object?>>' can't be returned from the method 'getCurrencyRate' because it has a return type of 'Future'
How can I make the function return an int (which is the result of the query) instead of a list ?
Thanks
Future<double> getCurrencyRate(String symb) async{
final db = await instance.database;
final result = await db.rawQuery("SELECT rate FROM Currencies WHERE symb = '$symb'");
return result.isNotEmpty ? result.first["rate"] : 0.0;
}
I'm creating a post that uploads data to Firestore's sub-collection and brings it up to MyBookmark page. It's good to create a sub-collection and upload data simply. And now I'd like to add a 'data duplication prevention' function here.
If the post is already saved in the bookmark, should not upload it.
For this purpose, I would like to check if the post is already in the collection when I press the bookmark button.
IconButton(
onPressed: () async {
//get userModel
UserModelState _userModelstate =
Provider.of<UserModelState>(context, listen: false);
//=========================================
//duplication data test
DocumentReference bookmarkRef = Firestore.instance
.collection(COLLECTION_USERS)
.document(_userModelstate.userModel.userKey)
.collection(COLLECTION_BOOKMARk)
// .where(KEY_BOOKMARK_PRODUCTKEY, isEqualTo: productKey)
.document();
DocumentSnapshot bookmarkSnapshot = await bookmarkRef.get();
//test (return "No exist")
if(bookmarkSnapshot.exists) {
print("Yes exist");
} else {
print("No exist");
}
I tried writing a code to check if there was data in the collection, but it is always printed as "No exist".
How can I confirm the existence of a specific document in collection?
Thank you.
If the productKey is supposed to be unique in the Bookmark collection of the user, consider using the productKey as the document ID. Since document IDs are by definition unique within their collection, using them guarantees unique product keys without you having to write any code for it.
That said, you current code can't work because you call document(). Whenever you call document() without any parameters, it generates a reference to a new unique document. And since you immediately call get() on that reference, the document will (also: by definition) not exist yet.
To check if a document with a specific product ID exist, you will need to run a query:
CollectionReference bookmarksRef = Firestore.instance
.collection(COLLECTION_USERS)
.document(_userModelstate.userModel.userKey)
.collection(COLLECTION_BOOKMARk);
Query bookmarkQuery = bookmarksRef.where(KEY_BOOKMARK_PRODUCTKEY, isEqualTo: productKey);
QuerySnapshot bookmarkSnapshot = await bookmarkQuery.get();
if (bookmarkSnapshot.size > 0) {
print("product key already in use");
}
I have this code:
class SharedPreferencesHelper {
static Future<int> getYear() async {
final prefs = await SharedPreferences.getInstance();
print("GET1");
print(prefs.getInt("year"));
return prefs.getInt("year");
}
}
print above correctly outputs 2019 on GET1 (I indeed set prefs.setInt('year', 2019))
year = SharedPreferencesHelper.getYear();
print("GET2");
print(year);
But print above return Instance of Future<int> on GET2, but I expected 2019.
I've been checked the awaits/async, I kinda confused where do I am missing.
I need to use the 2019 value to be used on DateTime.parse().
Please help, thanks.
You should also await the second call to SharedPreferences
year = await SharedPreferencesHelper.getYear();
I want to save an image inside the sqflite database and the later on, I want to display it in a SliverAppBar as a background. Till now I am able to save the image(not sure if it is right, but throws no error XD):
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path;
File newImage = await _image.copy('$path/${recipeName.text}.png'); //_image already taken with image_picker plugin
String base64Encoded = base64Encode(newImage.readAsBytesSync());
And this String I am saving inside the database. But I also want to display. And as far I know, I have to get the String, but from now I on, I do not know anything how to get further. I have written a function to get the String, but do not know what I should do with this String. The function looks like this:
Future fetchRecipe(String name) async{
var dbHelper = new DBHelper();
Future<List<Recipes>> recipes = dbHelper.getSpecRecipe(name);
return recipes;
}
The getSpecRecipe(name) points to this function:
Future<List<Recipes>> getSpecRecipe(String recipeName) async{
List<Map> list = await _db.rawQuery("SELECT * FROM recipes WHERE name = ?", [recipeName]);
List<Recipes> recipes = new List();
for(int i =0; i < list.length; i++){
recipes.add(new Recipes(list[i]["id"], list[i]["name"], list[i]["definition"], list[i]["duration"], list[i]["favorite"], list[i]["timestamp"], list[i]["image"], list[i]["backgroundColor"]));
}
return recipes;
}
It would be awesome, if somebody would be able to solve my problem. Thanks in advanceXD
From the snippets provided, it seems that you're trying to save the image as a base64 on your database. And as mentioned by #Nordeast in the comments, it's better to save the image on the device's storage and store the file path instead. Also, given the snippets provided, it's difficult to replicate the behavior locally.
I am trying to fetch data from Sqlite database using a sqlite plug-in in phonegap but I seem to be missing something. It doesn't report error when I checked the logcat but instead the database was opened successfully but my code won't fetch the data.
Below is my code so far...
function ViewData(id){
var db = window.sqlitePlugin.openDatabase("mydb", "1.0", "mydb", 100000);
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM mytable WHERE userid=?', [id],
function(transaction, result) {
var row = result.rows.length;
if(row>0){
//fetch saved data
alert(result.rows.item(0)['lname']);
}
},errorHandler);
},errorHandler,nullHandler);
return ;
}
Note:
1. The error handler, success handler and null handler are well coded.
Please, any help is appreciated.
Sorry guys, i was calling the function before onDeviceReady