I am currently working on getting all the Data object from a certain user. I thought I am already getting it, but then I noticed that it only return a DATA the second time I click the button ( means async is not working ) If you can advice, that would be a great help! Thanks!
async getData(UID) {
let container = [];
var firebaseRef = this.afd.database.ref();
let qwee = await firebaseRef.child('AllData/')
.orderByChild("UserID")
.equalTo(UID)
.on("child_added", function(snapshot) {
container.push(snapshot.val());
});
return container;
}
This is the calling function
async LoadUserData(){
this.Data = await this.provider.getData("Tom");
}
You seem to be mixing callbacks and promises.
You will need to wrap the callback in a promise and then await it.
async getData(UID) {
let container = [];
var firebaseRef = this.afd.database.ref();
let qwee = await new Promise(function(resolve,reject){
return firebaseRef.child('AllData/')
.orderByChild("UserID")
.equalTo(UID)
.on("child_added", function(snapshot) {
resolve(snapshot.val());
//container.push(snapshot.val());
});
});
container.push(qwee);
return container;
}
Related
I want to get all the Values of the map which is under "Subjects" field. And I also want to listen if any updates or changes made to those values. I actually want to add al those values and store in a variable. Can someone please tell me how can i achieve this?
Here is the structure of the collection.
This is how im adding the subjects whenever a user enters the subject name
onPressed: () async {
temp = qrdataFeed.text;
int index = qrdataFeed.text.indexOf('-');
subject = qrdataFeed.text.substring(0, index);
print("Subject name is $subject");
numberOfClasses = await FirebaseFirestore.instance
.collection('tutors')
.doc(uid)
.get()
.then((doc) async {
Map<String, dynamic> map = await doc.data();
if (!map.containsKey('Subjects')) {
await tutor_details.doc(uid).set({
'Subjects': {'$subject': initialValue},
}, SetOptions(merge: true));
}
if (doc.data()['Subjects']['$subject'] !=
'$subject') {
if (!map.containsKey('$subject')) {
await tutor_details.doc(uid).set({
'Subjects': {'$subject': initialValue}
}, SetOptions(merge: true));
}
}
var val = await doc.data()['Subjects']['$subject'];
return val;
});
if (!mounted) return;
setState(() {
qrData = qrdataFeed.text;
scanned = true;
print('done');
//if (temp != qrdataFeed.text)
numberOfClasses += 1;
print('$numberOfClasses is printed');
});
await tutor_details.doc(uid).set({
'Subjects': {'$subject': numberOfClasses},
}, SetOptions(merge: true));
}
},
Posting the #NisanthReddy's solution as a Community Wiki for visibility.
A better architecture would be to have one class at the root to handle all your transactions and to also notify any listener in your code.
You should always call this class to update and you can add listeners to this class from any widget you want. This way you will have everything Firestore-related in one place.
I'm really new in Flutter programming. I've problem while try to get value from Future. After I get it, I want to deserialize it for further processing.
The return value from the Future is on JSON Array.
What should I do to solve this situation?
class _MyAppState extends State<BodyWidget>
{
bool loading = true;
List<Widget> listArray = [];
Dio dio = new Dio();
dynamic isicontent = null;
Future<dynamic> getOrderHistory() async {
final String pathUrl = "http://p.q.r.s/mobile/QIXGetShipmentHistory/" + await FlutterSession().get("MobileUsername");
var responseDio = await dio.get(pathUrl, options: Options( headers: {'Content-Type': 'application/json; charset=UTF-8' } ) );
print(responseDio.data); // It's works fine here...
return responseDio.data;
}
void renderIconShipmentOrderHistory()
{
var resultRespon = getOrderHistory();
print(resultRespon); //the problem is here...
}
}
The return statement needs to return a Future; something alike:
return dio.get(
pathUrl,
options: Options(
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
)
)
The async keyword from the signature likely can be removed, as there is no more await.
Obviously, not returning a Future but awaiting the result may be the other option.
I have list, I want to save in sharepreferences,
setString('key',json.encode(temporaryData));
When I try to get this value, only show Instance of Future<dynamic>
but when i print that json.encode show it value
[{"name":"Stranger","birthDate":"","idCardNum":"-1","currentTime":1593598133479,"imageFlag":1,"imageName":"-1_1_1593598133479.png","type":-1,"tempratrue":"36.3","mask":0}]
Future<SharedPreferences> storage() {
return SharedPreferences.getInstance();
}
void setTempData(String temp) async {
SharedPreferences sharedPreferences = await storage();
await sharedPreferences.setString('datas', temp);
}
getTempData(String key) async {
SharedPreferences sharedPreferences = await storage();
await sharedPreferences.get(key);
}
_getTemp() async {
DateTime start = DateTime.now().subtract(Duration(seconds: 5));
DateTime end = DateTime.now();
Map data = {'pass': '123456', 'startTime': '$start', 'endTime': '$end'};
var response = await http.post('$urlApiQr:8080/newFindRecords', body: data);
var jsonData = json.decode(response.body);
var jsEnc = json.encode(response.body);
TempJson tempJson = TempJson.fromJson(jsonData);
var parse = json.decode(tempJson.config);
setState(() {
dataList = parse;
temporaryData = dataList.toSet().toList();
setTempData(json.encode(temporaryData));
//try to print value
print('$start and $end');
print(parse);
print(getTempData('datas'));
});
}
Is there a solution to my problem?
UPDATE 2.0
you have to add await anywhere your are requesting value from a Future.. as the below method return a Future as you can see from your error, just add await keyword from where you are requesting a value,
for example
print(await getTempData(key));
UPDATE
return keyword missing
getTempData(String key) async {
SharedPreferences sharedPreferences = await storage();
//you missed the return keyword here
return await sharedPreferences.get(key);
}
original answer
dont miss the await keyword
var thestring = await sp.getString('the_key');
var theJsonObj = json.decode(thestring);
this is my assumption, please post more code
Hi I'm trying to get a Future to be used as a normal boolean, how do I use this function as the determiner for a normal boolean without it giving me an incorrect type error?
Future<bool> checkIfOnAnyChats() async {
FirebaseUser user = await _auth.currentUser();
final QuerySnapshot result = await _firestore
.collection('chats')
.where('members', arrayContains: _username)
.getDocuments();
final List<DocumentSnapshot> documents = result.documents;
if(documents.length > 0) {
return Future<bool>.value(true);
}else{
return Future<bool>.value(false);
}
}
How do I apply it to a normal type boolean and not get this error? Thanks.
you don't need to convert bool into future, as you are in async method it will return future only.
you can get that value in initstate, you can not get value outside any method.
bool _isInChat;
#override
void initState() {
super.initState();
CheckIfOnAnyChats().then((value){
SetState((){
_isInChat = value;
});
});
}
I'm an Android developer and recently I've started working on a project based on firebase cloud functions and firestore database. I'm writing an HTTP trigger function that will take two parameters and compare that parameter value with the firestore data value and if the value matches then return a response of true or else false.
Duplicate Question:
Yes, there are some question already asked related to mine but they are not similar:
Firestore + cloud functions: How to read from another document
Firebase HTTP Cloud Functions - Read database once
Firebase Docs says:
Cloud Firestore supports create, update, delete, and write events
I want to read firestore value from HTTP trigger.
What I have tried:
exports.userData = functions.https.onRequest((req, res) => {
const user = req.query.user;
const pass = req.query.pass;
});
I'm pretty much stuck at this part. Any help will be greatly appreciated. Thanks
P.S. I have very limited knowledge related to JS/TypeScript/NodeJS
a bit late, but for any one else stumbling upon this.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someMethod = functions.https.onRequest((req, res) => {
var stuff = [];
var db = admin.firestore();
db.collection("Users").doc("7vFjDJ63DmhcQiEHwl0M7hfL3Kt1").collection("blabla").get().then(snapshot => {
snapshot.forEach(doc => {
var newelement = {
"id": doc.id,
"xxxx": doc.data().xxx,
"yyy": doc.data().yyy
}
stuff = stuff.concat(newelement);
});
res.send(stuff)
return "";
}).catch(reason => {
res.send(reason)
})
});
Thanks to Ruan's answer, here's an example for onCall(..) variation:
exports.fireGetColors = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
var colors = {};
var db = admin.firestore();
db.collection('colors')
.get()
.then(snapshot => {
snapshot.forEach(doc => {
var key = doc.id;
var color = doc.data();
color['key'] = key;
colors[key] = color;
});
var colorsStr = JSON.stringify(colors, null, '\t');
console.log('colors callback result : ' + colorsStr);
resolve(colors);
})
.catch(reason => {
console.log('db.collection("colors").get gets err, reason: ' + reason);
reject(reason);
});
});
});
In 2022, I am trying to do this thing in "Modular" way as what firebase has for version >= 9. Using typescript too as an addition :). Thanks to Ruan for the inspiration.
So, here is how I made it ( similar to the following ):
import * as functions from "firebase-functions";
import { getFirestore } from "firebase-admin/firestore";
import { initializeApp } from "firebase-admin/app";
initializeApp(functions.config().firebase);
export const someMethod = functions.https.onRequest((req, res) => {
let stuff: any[] = [];
let db = getFirestore();
db.collection("Users").doc("7vFjDJ63DmhcQiEHwl0M7hfL3Kt1").collection("blabla").get().then(snapshot => {
snapshot.forEach(doc => {
var newelement = {
"id": doc.id,
"xxxx": doc.data().xxx,
"yyy": doc.data().yyy
}
stuff = stuff.concat(newelement);
});
res.send(stuff)
return "";
}).catch(reason => {
res.send(reason)
})
});