Okay. I've been using Flutter for a little more than a year now. I've been using this same code in almost every app, and it works. For some reason, it doesn't work in this new app that I'm building.
String testString(DocumentSnapshot doc, String val) {
try {
if (doc == null) {
return "error! DB not found!";
}
if (doc[val] == null) {
return "'" + val + "' doesn't exist in DB";
}
return doc[val];
} catch (e) {
return "Error: something went wrong";
}
}
I've also tried this:
String testUndString(DocumentSnapshot doc, String val) {
try {
return doc != null ? (doc[val] != null ? doc[val] : "undefined") : "undefined";
} catch (e) {
return "Error: something went wrong";
}
}
and this:
String testUndString(DocumentSnapshot doc, String val) {
try {
return doc.data != null ? (doc[val] != null ? doc[val] : "undefined") : "undefined";
} catch (e) {
return "Error: something went wrong";
}
}
After doing some searching, it looks like I've done this correctly, but it still returns the error:
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.)
Try this code:
if (doc is !DocumentSnapshot) {
return "error! DB not found!";
}
Related
I am trying to add a function so that whenever a button is pressed, it will take my variables and look through all documents in my database. Then when it finds a document that matches the variables, it will delete that item. However, I keep getting an error message that I need a ")" after the (doc). Is there a better way to run through all the items to delete them, or am I doing something wrong with the snapshots/forEach statements?
Object deleteUser() {
// Call the user's CollectionReference to add a new user
if(name!="" && type!="" && location!="") {
items.snapshots().forEach(
(doc) => if(doc.data['name']==deleteName && doc.data['type']==deleteType && doc.data['location']==deleteLocation => doc.delete();));
return items;
}else{
return "There was a null error";
}
}
Your forEach loop is what's throwing the error as it isn't valid dart. I cleaned it up, this should work for you.
Object deleteUser() {
// Call the user's CollectionReference to add a new user
if (name != "" && type != "" && location != "") {
for (var doc in items.snapshots()) {
if (doc.data['name'] == deleteName &&
doc.data['type'] == deleteType &&
doc.data['location'] == deleteLocation) {
doc.delete();
}
}
return items;
} else {
return "There was a null error";
}
}
I am trying to read a document from a database in firebase and show the info at the UI. Any idea why is it not working?
Viewmodel:
var leid = MediatorLiveData<Gas>()
init {
initializeDocument()
}
fun initializeDocument(){
mFirestore?.collection("expenditures")?.document("ASfavaftaseacdadf")?.get()?.addOnSuccessListener { document ->
if (document != null) {
Log.d("TAG", "DocumentSnapshot data: ${document.data}")
var gastl = document.toObject<Gas>()!!
leid.value=gastl
} else {
Log.d("TAG", "No such document")
}
}
?.addOnFailureListener { exception ->
Log.d("TAG", "get failed with ", exception)
}
}
After that, I use databinding for the UI. When I try to execute the code, I dont get any log or anything; It is like the function never execute.
Thanks in advance.
When trying to make a call to a Cloud Function I get a "CloudFunctionsException"
The code of the exception is "INTERNAL
The message is "Response is not valid JSON object."
Describe the bug
To Reproduce
Steps to reproduce the behavior:
- My call from the application is
HttpsCallable _getName;
_getName = CloudFunctions.instance.getHttpsCallable(functionName: 'getName',);
try {
HttpsCallableResult resp = await _getName.call(<String, dynamic>{'name': name,});
Scaffold.of(context).showSnackBar(SnackBar(content: Text("${resp.data}")));
} on CloudFunctionsException catch (e) {
showErrorMessage(context, 'Cloud functions exception with code: ${e.code}, and Details: ${e.details}, with message: ${e.message} ');
} catch (e) {
showErrorMessage(context, e.toString());
}
My Cloud Function is written as so:
exports.getName = functions.https.onCall((data, context) => {
return {
"data" : "You hit the call at least!"
};
});
Expected behavior
In my response, I should get back the data: "You hit the test call". Instead, I get the error
Additional context
When I make calls to the same function but with the HTTP package and receive it on the back end with "onRequest", it works.
void _checkPersonsNameGET(String name)async{
try {
http.Response resp = await http.get(_cloudFunctionUrl,, );
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("${resp.body}", style: TextStyle(color: Colors.green))));
} catch (e) {
showErrorMessage(context, e.toString());
}
}
void _checkPersonsNamePOST(String name)async{
try {
http.Response resp = await http.post(_cloudFunctionUrl, body: { "name" : name } );
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("${resp.body}", style: TextStyle(color: Colors.green))));
} catch (e) {
showErrorMessage(context, e.toString());
}
}
exports.getName = functions.https.onRequest((request, response) => {
const name = request.query.name || request.body.name;
switch (name) {
case 'Andrew':
request.query.name ? response.send("Na he is the boi Q!") : response.send("Na he is the boi B!");
break;
case 'Brett':
request.query.name ? response.send("Na just wierd! Q") : response.send("Na just wierd! B");
break;
case 'Eddie':
request.query.name ? response.send("My brother but yeah! Q") : response.send("My brother but yeah! B");
break;
case 'James':
request.query.name ? response.send("The biggest! Q") : response.send("The biggest! B");
break;
default:
request.query.name ? response.send("Dunno who that is! Q") : response.send("Dunno who that is! B");
break;
}
});
It's a mock application and can be seen here
https://github.com/earyzhe/firebase_cloud_functions_play
In my case, the cloud function was in a file that was not exported in the index file. Make sure your function is properly exported and has been deployed properly.
I have a method and it throws an error so I can catch it in my event and display it to the user, like this:
Meteor.methods({
addPlayer: function(nickname) {
if (nickname == "") {
throw new Meteor.Error('empty-nickname', 'You must choose a nickname');
} else {
Player.insert({
nickname: nickname,
});
}
},
})
and in my event
'submit form': function (e) {
e.preventDefault();
var nickname = $('input').val();
Meteor.call('addPlayer', nickname, function(error, result) {
if (error) {
console.log(typeof error);
console.log(error);
}
});
}
However, meteor still throws an Exception while simulating the effect of invoking 'addPlayer', and the error variable is not an error object, but a string with the same message as the console log, so I get two errors in my console instead of an error object.
Wrapping method.call in a try/catch does not work.
What am I missing here?
-- Edit
Here is an print screen of the result:
Image link for full resolution: http://i.stack.imgur.com/zABar.png
Throw the error only on the server. Wrap it inside if(!this.isSimulation) {}
Meteor.methods({
addPlayer: function(nickname) {
if (nickname == "") {
if(!this.isSimulation) {
throw new Meteor.Error('empty-nickname', 'You must choose a nickname');
}
} else {
Player.insert({
nickname: nickname,
});
}
},
})
I'm attempting to use Meteorjs Accounts on the server to create a new user and then send them an email to set their initial password. The idea is that an admin user can add new users.
I can successfully add the new user (I can see the new user ID in the server console if I log it), but that ID is never returned to the client. This is my server-side
Meteor.methods({
createNewUser: function(email){
return Accounts.createUser({email: email});
}
});
And the relevant client-side JS:
if (isNotEmpty(email) && isEmail(email)) {
Meteor.call("createNewUser", email, function(ret){
if (typeof ret.message !== 'undefined') {
if (ret.message === 'Email already exists. [403]') {
alert("exists");
} else {
alert("not created");
}
} else {
Accounts.sendEnrollmentEmail(ret, function(err){
if (err){
alert("email didn't get sent");
} else {
alert('success');
}
});
}
});
}
I get this in my browser console:
Exception in delivering result of invoking 'createNewUser': TypeError: Cannot read property 'message' of undefined
It's probably worth noting that I also get the "exists" alert if I try to submit the same email address twice in a row, so the error is getting returned to the client just fine.
The first argument in callback is always error object.
error equals null if everything is fine.
Meteor.call('createNewUser', email, function( error, result ){
if( error ){
console.error("ERROR -> ", error )
}else{
console.log("User was created!")
}
})
but that ID is never returned to the client.
Thats because you don't have any console.log on the client. also the meteor call look incorrect.
if (isNotEmpty(email) && isEmail(email)) {
Meteor.call("createNewUser", email, function(err,result){
if (typeof ret.message !== 'undefined') {
if (ret.message === 'Email already exists. [403]') {
alert("exists");
} else {
console.log(result) //here for example you should get the id
}
} else {
Accounts.sendEnrollmentEmail(ret, function(err){
if (err){
alert("email didn't get sent");
} else {
alert('success');
}
});
}
});
}