Unhandled Exception: Invalid argument: Instance of 'TextEditingController' - flutter

Here is my code, I want to store data to Firebase Database when user enter button but getting the following error
onTap: () {
if(_controllershopname.text==''||_controllerstreet.text==''||_controllershopnumber.text==''||_controllercity.text==''||_controllerstate.text=='')
{
Fluttertoast.showToast(msg: "Please Fill all the fields");
}else{
DatabaseReference databseRefrence = FirebaseDatabase.instance.reference().child("ShopKeeper");
databseRefrence.child(widget.number).push().set(
{
'Name':widget.userName,
'ShopName': _controllershopname.text,
'ShopNumber':_controllershopnumber.text,
'ShopStreet':_controllerstreet.text,
'ShopCity':_controllercity.text,
'ShopState':_controllerstate.text,
'OnlineDelivery':"Yes",
});
Here is the error
E/flutter (26078): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument: Instance of 'TextEditingController'
E/flutter (26078): #0 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:392:7)
E/flutter (26078): #1 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:389:9)
E/flutter (26078): #2 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (26078): #3 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:387:13)
E/flutter (26078): #4 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:389:9)
E/flutter (26078): #5 _LinkedHashMapMixin.forEach (dart:collection-

Did you create instances of your "TextEdittingControllers"? If you did, then you should try trimming your text before saving to the database:
onTap: () {
if(_controllershopname.text==''||_controllerstreet.text==''||_controllershopnumber.text==''||_controllercity.text==''||_controllerstate.text=='')
{
{
Fluttertoast.showToast(msg: "Please Fill all the fields");
}else{
DatabaseReference databseRefrence = FirebaseDatabase.instance.reference().child("ShopKeeper");
databseRefrence.child(widget.number).push().set(
{
'Name':widget.userName,
'ShopName': _controllershopname.text.trim(),
'ShopNumber':_controllershopnumber.text.trim(),
'ShopStreet':_controllerstreet.text.trim(),
'ShopCity':_controllercity.text.trim(),
'ShopState':_controllerstate.text.trim(),
'OnlineDelivery':"Yes",
});

Related

Unhandled Exception: [firebase_functions/internal] INTERNAL

I've a Flutter App Project which contains levels of permission, so, my main objective with this is allow an manager delete a user, making him not allowed anymore to login, deleting from FirebaseAuth.
I've a permission called "Deactivated" to prevent the user from logging in, but i really want to remove from FirebaseAuth too.
The only way I've found is using the Firebase Cloud Functions, so I tried to do very similar to FlutterFire Docs
When i execute using PostMan, it works perfectly, the user test is deleted as expected:
METHOD: Post
Url: https://us-central1-<DATABASE_NAME>.cloudfunctions.net/deleteUserByEmail/
Body -> Raw:
{
"userEmail": "test#gmail.com"
}
My index.js
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
exports.deleteUserByEmail = functions.https.onRequest(async (request, response) => {
try {
const userEmail = request.body.userEmail;
admin.auth().getUserByEmail(userEmail)
.then(userRecord => {
const uid = userRecord.uid
return admin.auth().deleteUser(uid)
.then(() => {
console.log("Successfully deleted user");
response.status(200).send('Delete User');
return
})
}).catch(error => {
throw new functions.https.HttpsError('invalid-argument', error.HttpsError);
});
} catch (err) {
throw new functions.https.HttpsError('invalid-argument', "Error passing arguments into");
}
})
Part of my code that calls the code Flutter code:
HttpsCallable callable =
FirebaseFunctions.instance.httpsCallable('deleteUserByEmail');
try {
final resp = await callable.call(<String, dynamic>{
"userEmail" : userModel.email,
});
} on FirebaseFunctionsException catch (e) {
debugPrint(e.toString());
}
Once i tap the button, i receive this error code:
E/flutter (20323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_functions/internal] INTERNAL
E/flutter (20323):
E/flutter (20323): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2 MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #3 HttpsCallable.call
package:cloud_functions/src/https_callable.dart:49
E/flutter (20323): <asynchronous suspension>
E/flutter (20323):
E/flutter (20323): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2 MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
After some research I've found that some people had that problem when their code wasn't inside a tryCatch block, but mine was since ever...
I've tried to start admin.initializeApp() parsing the credentials and databaseURL even though my FlutterFire CLI is configured, but didn't work too.

How to convert the type Future<List<T>> to <List<T>> in fultter?

everyone! I was developing e-commerce flutter app with doofinder APIs.
But I faced a thorny problem. I tried to get data from doofinder(it's just search service) API then present to screen. I added screen-shots.
Future<List<Product>> fetchProduct(query) async {
var response = await http.get(
Uri.parse(
'https://eu1-search.doofinder.com/5/search?hashid=30a5f&query=$query'),
// Send authorization headers to the backend.
headers: {'Authorization': 'c59dadc5d822ca2b134f170'},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(jsonDecode(response.body)['results'].toList().runtimeType);
return jsonDecode(response.body)['results'].toList().cast<List<Product>>();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
then,
onChanged: (_) => EasyDebounce.debounce(
'tFMemberController',
const Duration(milliseconds: 800),
() {
isSearchStarted =
textController!.text.isNotEmpty &&
textController!.text.trim().length > 0;
print('isSearchStarted $isSearchStarted');
if (isSearchStarted) {
print('${textController!.text.trim()}');
searchedProducts =
fetchProduct(textController!.text)
as List<Product>;
print(searchedProducts);
}
setState(() {});
},
),
And this is error log.
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Future<List<Product>>' is not a subtype of type 'List<Product>' in type cast
E/flutter ( 5295): #0 _SearchPageState.build.<anonymous closure>.<anonymous closure> (package:s4s_mobileapp/search/page_search.dart:151:41)
E/flutter ( 5295): #1 EasyDebounce.debounce.<anonymous closure> (package:easy_debounce/easy_debounce.dart:44:22)
E/flutter ( 5295): #2 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 5295): #3 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter ( 5295): #4 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter ( 5295): #5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter ( 5295):
I/flutter ( 5295): List<dynamic>
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'CastList<dynamic, List<Product>>' is not a subtype of type 'FutureOr<List<Product>>'
E/flutter ( 5295): #0 fetchProduct (package:s4s_mobileapp/search/page_search.dart:41:58)
E/flutter ( 5295): <asynchronous suspension>
E/flutter ( 5295):
This makes me crazy.
I want you to take a closer look at the pictures below and find a suitable solution please.
Change
jsonDecode(response.body)['results'].toList().cast<List<Product>>();
to this:
jsonDecode(response.body)['results'].toList().cast<Product>();
The cast method already knows that you are working with lists and only wants to know the type of the elements, but not the type of the list itself.
EDIT: You also need to change:
searchedProducts = fetchProduct(textController!.text) as List<Product>;
to this:
searchedProducts = fetchProduct(textController!.text) as Future<List<Product>>;
You have to work with futures as your result is processed asynchronously. In the widget tree you have to use FutureBuilder which takes a future and builds your list as you want.

flutter zone vs future

I read about Zone and have used Futures in many languages. I know about Event Loop and that Dart is single threaded. However, when I write following code I could not differentiate how differently it will work and when to use one over another.
What is the difference between zone and future?
For example here:
runZoned(() async {
// Do Something
}, onError: (e, stackTrace) {
print(e);
});
Vs
someAsyncCall().catchError((e) {
print(e);
});
Futures error handling
Zones
What is a Future
Edit 1: I used runZonedGuarded instaed runZoned because runZoned.onError is deprecated.
Flutter : 'onError' is deprecated on runZoned function
Hi! With runZoned you can basically Handling asynchronous errors that are commonly caused by futures (http request, etc). The concept is similar to a try-catch in synchronous code. With Future you cannot do that.
runZoned example:
runZonedGuarded(() {
_timerError();
}, (error, stack) {
print('Uncaught error runZoneGuard: $error');
});
resullt:
I/flutter (13567): Uncaught error runZoneGuard: asynchronous error
Future example:
someCall().then((value) {
_timerError();
}, onError: (value) {
print('Uncaught error onError: $value');
}).catchError((e) {
print('Uncaught error catchError: $e');
});
result:
E/flutter (13567): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: asynchronous error
E/flutter (13567): #0 _MyHomePageState._timerError.<anonymous closure> (package:async_study/main.dart:60:7)
E/flutter (13567): #1 _rootRun (dart:async/zone.dart:1418:47)
E/flutter (13567): #2 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #3 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter (13567): #4 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter (13567): #5 _rootRun (dart:async/zone.dart:1426:13)
E/flutter (13567): #6 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #7 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1260:23)
E/flutter (13567): #8 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (13567): #9 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (13567): #10 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (13567): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
And the '_timerError()' method used to trhow a async error:
void _timerError() {
Timer.run(() {
throw "asynchronous error";
});
}

Unhandled Exception: [firebase_functions/not-found] NOT_FOUND -Flutter

I am trying to implement the twilio_voice: ^0.0.9 plug in and register my firebase app at the same time but, when I run my registration function I get the error:
E/flutter (27321): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [firebase_functions/not-found] NOT_FOUND
E/flutter (27321):
E/flutter (27321): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:607
E/flutter (27321): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:156
E/flutter (27321): <asynchronous suspension>
E/flutter (27321): #2 MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
E/flutter (27321): <asynchronous suspension>
E/flutter (27321): #3 HttpsCallable.call
package:cloud_functions/src/https_callable.dart:35
E/flutter (27321): <asynchronous suspension>
E/flutter (27321): #4 _TextScreenState.register
package:buddiesDrivers/CallScreen/TextScreen.dart:72
E/flutter (27321): <asynchronous suspension>
E/flutter (27321):
E/flutter (27321): #0 MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:39
E/flutter (27321): <asynchronous suspension>
E/flutter (27321): #1 HttpsCallable.call
package:cloud_functions/src/https_callable.dart:35
E/flutter (27321): <asynchronous suspension>
I am have firebase implemented and running and I am getting my token when logging in. The app seems to fail when calling the httpsCallable("voice-accessToken") in the app. Here is the function:
register() async {
print("voip-registtering with token ");
print("voip-calling voice-accessToken");
final function =
FirebaseFunctions.instance.httpsCallable("voice-accessToken");
final data = {
"platform": Platform.isIOS ? "iOS" : "Android",
};
final result = await function.call(data);
print("voip-result");
print(result.data);
String androidToken;
if (Platform.isAndroid) {
androidToken = await FirebaseMessaging.instance.getToken();
print("androidToken is " + androidToken);
}
TwilioVoice.instance
.setTokens(accessToken: result.data, deviceToken: androidToken);
}
Any help in the right direction would be appreciated

Unhandled Exception: Invalid argument: Instance of 'CartItemModel'

i am working on a store application and after the user places an order, i will like to store that order details in the firebase firestore. the function for carrying out that call after the button is pressed is this
addOrderDetails() {
final user = Provider.of<UserProvider>(context, listen: false);
writeOrderDetailsForUser({
"userId" : user.user.uid,
"description" : "Cash on delivery",
"status" : "pending",
"createdAt": DateTime.now().millisecondsSinceEpoch.toString(),
"totalPrice" : user.userModel.totalCartPrice,
"cart" : user.userModel.cart,
"address" : widget.addressId,
"phone" : user.userModel.phone,
}).whenComplete(() async {
for (CartItemModel cartItem in user.userModel.cart){
bool value = await user.removeFromCart(cartItem: cartItem);
if(value) {
user.reloadUserModel();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Item has been successfully removed from cart"),));
}else {
print(
"item has not been removed from cart please try again"
);
}
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
"Your order has been successfully created, please we will call you in a few minutes to confirm your order"),));
});
changeScreenReplacement(context, NavigationController());
}
Future writeOrderDetailsForUser(Map<String, dynamic> data) async
{
await EcommerceApp.firestore
.collection(EcommerceApp.collectionOrders)
.document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID) + data['createdAt'])
.setData(data);
}
}
However i am getting this error anytime i make the function call
I/flutter (24853): cart items are: Instance of 'CartItemModel'
E/flutter (24853): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Invalid argument: Instance of 'CartItemModel'
E/flutter (24853): #0 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:419:7)
E/flutter (24853): #1 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #2 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:409:9)
E/flutter (24853): #3 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #4 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:416:9)
E/flutter (24853): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (24853): #6 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:414:13)
E/flutter (24853): #7 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #8 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:416:9)
E/flutter (24853): #9 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (24853): #10 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:414:13)
E/flutter (24853): #11 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #12 StandardMethodCodec.encodeMethodCall (package:flutter/src/services/message_codecs.dart:551:18)
E/flutter (24853): #13 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:150:13)
E/flutter (24853): #14 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (24853): #15 MethodChannelDocumentReference.setData (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:28:43)
E/flutter (24853): #16 DocumentReference.setData (package:cloud_firestore/src/document_reference.dart:48:22)
E/flutter (24853): #17 _PaymentPageState.writeOrderDetailsForUser (package:maen/screens/placeOrderPayment.dart:349:10)
E/flutter (24853): #18 _PaymentPageState.addOrderDetails (package:maen/screens/placeOrderPayment.dart:316:5)
E/flutter (24853): #19 _PaymentPageState.build. (package:maen/screens/placeOrderPayment.dart:297:17)
The problem is caused because of this line
"cart" : user.userModel.cart,
Seems like your user.userModel.cart is the List of CartItemModel,
To overcome this you'll have to serialize this and then add to the database, because database doesn't know anything about CartItemModel,
Do something like this:
"cart" : user.userModel.cart.map((e)=>e.toJson()).toList();
In CartItemModel define the toJson function
As the details is less, I assume CartItemModel has fields like id , name and price
Map toJson() => {
'id': id,
'name': name,
'price' : price
};
This should solve your problem