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;
}
Related
I am working on a basic project where I want to implement search functionality on the user's collection. that functionality should use like query we have in sql.
Here is my code :
static Future<List> searchUser(String query) async {
final mongoDB = MongoDB();
final db = mongoDB.db;
var collection = db.collection("users");
var queryBuilder = where.eq(
'name',
query,
);
var cursor = await collection.find(queryBuilder).toList();
print(cursor);
return cursor;
}
I want to know how to implement such functionality.
I want to calculate how many documents are in a collection, not the length of the document. I have tried it with some code but what appears is the length of the character from my document name.
this my code :
StreamSubscription<DocumentSnapshot> userpost;
final DocumentReference documentReference =
Firestore.instance.document("product/$documentPost");
userpost = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.exists) {
for (int i = 0; i < datasnapshot.data.length; i++){
print(datasnapshot.data.length);
}
An Example Function to fetch Documents Count.
void countDocuments() async {
QuerySnapshot _myDoc = await Firestore.instance.collection('product').getDocuments();
List<DocumentSnapshot> _myDocCount = _myDoc.documents;
print(_myDocCount.length); // Count of Documents in Collection
}
You can use the count() function which was added in cloud_firestore version 4.0.0
Accepted answer might be a bad solution because you have to fetch all the documents just to count the number of documents. As per Firestore pricing, every document read is taken as 1 read count.
So a better solution is to use the count() function instead.
AggregateQuerySnapshot query = FirebaseFirestore.instance.collection('random_collection').count().get();
int numberOfDocuments = query.count;
count() is an Aggregation Query
PS: You might need to update your firebase plugins in pubspec.yaml.
With Cloud Firebase 2.0, there is a new way to count documents in a collection. According to reference notes, the count does not count as a read per document but a metaData request:
"[AggregateQuery] represents the data at a particular location for retrieving metadata without retrieving the actual documents."
Example:
final CollectionReference<Map<String, dynamic>> userList = FirebaseFirestore.instance.collection('users');
Future<int> countUsers() async {
AggregateQuerySnapshot query = await userList.count().get();
debugPrint('The number of users: ${query.count}');
return query.count;
}
I've been trying to understand why my query returns null object from server generated timestamp value.
Basically, I used onUpdate() trigger on my Firestore database and check, if the product is low on stock and make a reminder when the stock is <=5. This is my Node.js code and it currently works even tho it's got no proper responses.
const date = admin.firestore.FieldValue.serverTimestamp();
const reminder = {
productID : product.barcode,
date : date,
status: 'Order'
}
const docSnapShot = admin.firestore().collection('reminders').doc(product.barcode).get().then(documentSnapShot =>{
if(documentSnapShot.exists){
return admin.firestore().collection('reminders').doc(product.barcode).update({date: date}).then(res=> {
console.log('Document updated');
return null;
}).catch(error =>{
console.log('Error',error);
return null;
});
}
else{
exists = docSnapShot.exists;
return null;
}
});
Server successfully inserts the generated timestamp and even when manually added, It still retrieves a null object in Java/Android. Using FirestoreRecyclerView and an RecyclerView custom adapter and class. I tried ServerTimeStamp and double checked variable names, sequence and I still get a null object. I get proper productID and status values.
public reminderFirestore(Timestamp date, String productID, String status) {
this.productID = productID;
this.date = date;
this.status = status;
}
Has this something to do with my constructor and object type or did I mess up in the server/Node.js code?
You need to include the default empty constructor and getters for all fields. If only your timestamp is null, then you must not have a getter for timestamp.
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
I have that query
String queryMonthSize = "SELECT (julianday(Date('now')) -
julianday(date('now','-1 month')) FROM "+ TABLE_STATISTICS;
Which on sqlite it will return me the difference of the two dates.
How can i execute it on the android code so that i will return me the numerical value of the string?
Your implementation will be
queryMonthSizeIntValue = Integer.parseInt(queryMonthSize);
See the the static parseInt() method:
http://developer.android.com/reference/java/lang/Integer.html