Error with my project - The method 'collection' was called on null [duplicate] - flutter

This question already has answers here:
What is a NoSuchMethod error and how do I fix it?
(2 answers)
Closed 2 years ago.
Good,
I have a problem with my application, since it generates an error when pressing the add to cart button, it generates an error and it is not added in firebase, I already checked that the variables have their name correctly, however I cannot find how solve this error, I appreciate all the help you can give me to solve this error!
void checkItemInCart(String shortInfoAsID, BuildContext context)
{
EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsID)
? Fluttertoast.showToast(msg: "El artículo ya existe en el carrito")
: addItemToCart(shortInfoAsID, context);
}
addItemToCart(String shortInfoAsID, BuildContext context) {
List tempCartList = EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList);
tempCartList.add(shortInfoAsID);
EcommerceApp.firestore.collection(EcommerceApp.collectionUser)
.document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID))
.updateData({
EcommerceApp.userCartList: tempCartList,
}).then((v){
Fluttertoast.showToast(msg: "Artículo añadido al carrito");
EcommerceApp.sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);
Provider.of<CartItemCounter>(context, listen: false).displayResult();
});
}
The following NoSuchMethodError was thrown while handling a gesture:
The method 'collection' was called on null.
Receiver: null
Tried calling: collection("users")
When the exception was thrown, this was the stack:
0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
1 addItemToCart (package:e_shop/Store/storehome.dart:283:26)
2 checkItemInCart (package:e_shop/Store/storehome.dart:276:9)
3 sourceInfo.<anonymous closure> (package:e_shop/Store/storehome.dart:246:27)
4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#696c2
debugOwner: GestureDetector
state: ready
won arena
finalPosition: Offset(338.5, 338.3)
finalLocalPosition: Offset(32.5, 27.8)
button: 1
sent tap down
====================================================================================================

Declare this:
List tempCartList = List<>();
Then do this :
void checkItemInCart(String shortInfoAsID, BuildContext context)
{
EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsID)
? Fluttertoast.showToast(msg: "El artículo ya existe en el carrito")
: addItemToCart(shortInfoAsID, context);
}
addItemToCart(String shortInfoAsID, BuildContext context) {
tempCartList = EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList);
tempCartList.add(shortInfoAsID);
EcommerceApp.firestore.collection(EcommerceApp.collectionUser)
.document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID))
.updateData({
EcommerceApp.userCartList: tempCartList,
}).then((v){
Fluttertoast.showToast(msg: "Artículo añadido al carrito");
EcommerceApp.sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);
Provider.of<CartItemCounter>(context, listen: false).displayResult();
});
}

Related

Unhandled Exception: Null check operator used on a null value in flutter

I hope you are well, I will give you a bit of context about my problem...
I really don't know why this error happens and I've seen many similar publications but they haven't worked for me.
I'm new to flutter and I'm working on an app, but when the user wants to log out, the app crashes and shows the following error:
E/flutter (12659): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter (12659): #0 StatefulElement.state
package:flutter/…/widgets/framework.dart:4999
E/flutter (12659): #1 Navigator.of
package:flutter/…/widgets/navigator.dart:2543
E/flutter (12659): #2 Navigator.pushReplacement
package:flutter/…/widgets/navigator.dart:2105
E/flutter (12659): #3 MainCoordinator.logoutNavigation
package:domicilios/…/MainCoordinator/MainCoordinator.dart:62
E/flutter (12659): #4 UserActions.signOut.<anonymous closure>.<anonymous closure>
package:domicilios/…/View/ProfileTab.dart:222
E/flutter (12659): <asynchronous suspension>
This is the code that generates this error, I hope you can help me, thank you very much for your attention.
this is the class:
extension UserActions on _ProfileTabState {
void signOut(BuildContext context) {
AlertView.showAlertDialog(
model: AlertViewModel(
context,
const AssetImage('assets/logout.png'),
'Cierre de sesión en curso',
"¿Desear salir de la sesión actual?",
'Cerrar sesión',
"Cancelar", () {
_profileTabViewModel
.signOut()
.then((value) => coordinator.logoutNavigation(context: context));
}, () {
Navigator.pop(context);
}));
}
}
That's how I call it in the code:
onTap: () => signOut(context),
This is most likely due to the widget being unmounted before navigating.
You can check if the widget is mounted before navigating.
if (mounted) {
_profileTabViewModel.signOut().then((value) {
if (mounted) {
coordinator.logoutNavigation(context: context);
}
});
}
Also,
if(mounted){
Navigator.pop(context);
}

Unhandled Exception: NoSuchMethodError: Class 'FirebaseAuthException' has no instance getter '_message'

Help me pls.
I have this error.
10Q
Unhandled Exception: NoSuchMethodError: Class 'FirebaseAuthException' has no instance getter '_message'.
E/flutter ( 5700): Receiver: Instance of 'FirebaseAuthException'
E/flutter ( 5700): Tried calling: _message
await _auth
.signInWithEmailAndPassword(
email: _emailTextEditingController.text.trim(),
password: _passwordTextEditingController.text.trim(),
)
.then((authUser) {
setState(() {
firebaseUser = authUser.user;
});
}).catchError((error) {
showDialog(
context: context,
builder: (c) {
return ErrorAlertDialog(
message: error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
);
});
});
error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
You are being told that there is no getter named _message for FirebaseAuthException. If you go to the code for that class, or the documentation (here) and look at the methods you have available to you,
_message is not one.
There is one there (getErrorCode) that you should be able to compare with much easier.
I think that the _message was called on null, I am not sure about this.

Unhandled Exception: Bad state: No element in new version package

The first time I put the app on the Play Store, it was running with upgrade functionality and also display the upgrade dialog properly but now it is giving me the following error.
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: No element
ListMixin.firstWhere (dart:collection/list.dart:167:5)
NewVersion._getAndroidStoreVersion (package:new_version/new_version.dart:152:51)
<asynchronous suspension>
_LoginDemoState._checkVersion (package:sampleproject/loginPage.dart:1747:18)
In this, I have used new_version package 0.2.3 and this is my code
void _checkVersion() async {
final newVersion = NewVersion(
androidId: "com.abc.pqr",
);
final status = await newVersion.getVersionStatus();
print("localVersion==> ${status.localVersion}");
print("localVersion==> ${status.storeVersion}");
status.localVersion!=status.storeVersion?
newVersion.showUpdateDialog(
context: context,
versionStatus: status,
dialogTitle: "UPDATE!!!",
dismissButtonText: "Skip",
dialogText: "Please update the abc app from " + "${status.localVersion}" + " to " + "${status.storeVersion}",
dismissAction: () {
Navigator.pop(context);
},
updateButtonText: "Lets update",
):Container();
print("DEVICE : " + status.localVersion);
print("STORE : " + status.storeVersion);
}
but I got the above error. I changed the version package also but not working. I got the same error.pls help

Flutter : firebase MissingPluginException

I'm having this problem about flutter and firebase(realtime-database).
Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
Here is the error in terminal
error
// error message
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method Query#observe on channel plugins.flutter.io/firebase_database)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>
#1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#2 Query._observe.<anonymous closure> (package:firebase_database/src/query.dart:50:38)
#3 _runGuarded (dart:async/stream_controller.dart:820:24)
#4 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:215:7)
#5 _ControllerStream._createSubscription (dart:async/stream_controller.dart:833:19)
#6 _StreamImpl.listen (dart:async/stream_impl.dart:475:9)
#7 Stream.first (dart:async/stream.dart:1254:25)
#8 Query.once (package:firebase_database/src/query.dart:84:55)
#9 _IoTState.initState (package:flutter_try_iot/main.dart:36:13)
#10 StatefulElement._f<…>
I'm trying to get data from firebase to display in flutter app.
Here is my code main.dart
class _IoTState extends State<IoT> {
final getIot = FirebaseDatabase.instance.reference();
final getData = FirebaseDatabase.instance.reference().child('xxx-xxx');
String temperatue = "0";
String illuminance = "0";
List<String> temp = [];
List<String> light = [];
#override
void initState(){
getData.once().then((DataSnapshot snapshot){
if (snapshot.value == null) {
print("Item doesn't exist in the db");
} else {
print("Item exists in the db");
}
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF7ACADA),
title: Text(
"IoT ZigBee Simulation",
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF1A1244)
),
),
),
body: Column(
),
);
}
}
pubspec.yaml
firebase_core: ^0.4.5
firebase_database: ^3.1.6
flutter_icons: ^1.1.0
fl_chart: ^0.10.1
I follow instructions to add ios to firebase .ios add firebase
no issues found by flutter doctor
I follow other peoples suggestion to do flutter clean & flutter packages get, but still not able to fix this problem
https://github.com/flutter/flutter/issues/13971
terminal
Also pop up a window telling me The file “Runner.xcworkspace” has been modified by another application" everytime I execute flutter clean/ flutter packages get
I successfully connect to firebase yesterday, but after I close my simulator I start to receive error message
success picture
Please give me some solution or advice to fix this problem, thanks.
Please tell me if I need to provide additional information

How to fix "the method 'cancel' called on null" while working with http requests flutter

I'm trying to athenticate using APIs from a flutter app but i get these errors everytime i click Login Button
final resp = await http.post("http://192.168.73.5/myserv/login.php", body: {
"login": "login",
"apid": "re0b53fd92d4b1593db1880az322d66ea9d4",
"email": _email,
"pass": _password,
});
var __data =json.decode(resp.body);
if (__data.length == 0) {
final snackbar = SnackBar(
content: Text('Server error'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'error') {
final snackbar = SnackBar(
content: Text('Password or email is incorrect!'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'sucess') {
final snackbar = SnackBar(
content: Text('You are logged in'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) => HomeApp()));
}
}
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (29517): The following NoSuchMethodError was thrown while finalizing the widget tree:
I/flutter (29517): The method 'cancel' was called on null.
I/flutter (29517): Receiver: null
I/flutter (29517): Tried calling: cancel()
I/flutter (29517): When the exception was thrown, this was the stack:
My suggestion would be to take a look to your dispose method. There you might notice a statement calling a cancel method on something that was never initiated or used, only declared. In my case I got this error because at the disposed method I was trying to cancel a subscription to a Firebase service that I had not used. I never attached a listener to it, therefore when trying to cancel it, Flutter complained saying "the method cancel was called on null". I deleted the unnecessary line at dispose method and the error resolved. Hope the explanation helps somebody.