How to fix "the method 'cancel' called on null" while working with http requests flutter - 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.

Related

Flutter State not getting updated

i am trying to comment section in social media app in android,the issue is after making the post comment ,the newly added comment is not showing in real time,the state is not getting updated , i tried to check the order of function calls by making print data in console,
console log
I/flutter ( 2069): comment posted succesfully
10
I/flutter ( 2069): getcomments
I/flutter ( 2069): setstate called
)),
GestureDetector(
onTap: () async {
await CommentService().postComment(
commentText: controller.text, postid: widget.postid);
await CommentService().getCommentsdata(post_id: widget.postid);
setState(() {
controller.clear();
print('setstate called');
});
},

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.

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

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();
});
}

Why showcaseview throws error on first try?

Hey I am using ShowCaseView in my Flutterapp. When I first open my app, after registration there is no showcase, not even the icon which should be 'showcased' is shown. But when I am closing the app and opening it again it works just fine.
Thats the code referring to showcase:
class _HomeSearchPageState extends State<HomeSearchPage> {
final keyOne = GlobalKey();
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => ShowCaseWidget.of(context).startShowCase([
keyOne,
]),
);
}
And now the scaffold:
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(getTopBarSize()),
child: AppBar(
automaticallyImplyLeading: false,
title: Text(
'username',
style: TextStyle(fontSize: 14),
),
actions: <Widget>[
Showcase(
key: keyOne,
description: 'test',
child: IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch())
.whenComplete(() => setName());
}),
),
],
),
),)
I did exactly the same as in the Github example but still it throws this error the first time:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building IconTheme(color: Color(0xffffffff)):
The getter 'activeWidgetIds' was called on null.
Receiver: null
Tried calling: activeWidgetIds
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 ShowCaseWidget.activeTargetWidget
package:showcaseview/showcase_widget.dart:51
#2 _ShowcaseState.showOverlay
package:showcaseview/showcase.dart:171
#3 _ShowcaseState.didChangeDependencies
package:showcaseview/showcase.dart:164
#4 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4786
════════ Exception caught by rendering library ═════════════════════════════════
Each child must be laid out exactly once.
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by scheduler library ═════════════════════════════════
Exception: Please provide ShowCaseView context
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 6224 pos 12: '_children.contains(child)': is not true.
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
════════════════════════════════════════════════════════════════════════════════
These errors are kind a looped, so the debug console shows them all the time.
The only difference between the first app opening and the second one is: In the first one the user enters a registrationpage and after this he enters the page with the showcaseview. In the second the user enters directly the page with the showcaseview. How can this affect the showcase and more accurate why does this throw the errors?
Not sure if we share a similar issue but maybe my answer will help you somehow :). The issue occurs when I navigate to the page where I have Showcase widget, but it does not occur when I navigate "back" to the page from the other page.
Maybe you can check this page "This error is thrown if you haven't wrapped your widget with ShowCaseWidget. This is not the problem with the package itself."
Thus, I tried raising the level of the ShowCaseWidget in the main.dart and the issue was solved.
void main() {
// runApp(MyApp());
runApp(
ShowCaseWidget(
autoPlay: false,
autoPlayDelay: Duration(seconds: 8),
autoPlayLockEnable: false,
builder: Builder(
builder: (context) => MyApp(),
),
onStart: (index, key) {
print('onStart: $index, $key');
},
onComplete: (index, key) {
print('onComplete: $index, $key');
},
),
);
}
So far the app still works well. I will report again here in case any issues occur.

Check if popUntil possible / Check if named route in navigation stack

How can I check if there is a route with name workout in my navigation stack? Whenever I call popUntil and the route is not in my stack, I get:
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Navigator-[GlobalObjectKey<NavigatorState> _WidgetsAppState#9d229](dirty, state: NavigatorState#86712(tickers: tracking 2 tickers)):
'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2330 pos 12: '!_debugLocked': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=BUG.md
The relevant error-causing widget was
MaterialApp
lib/main.dart:58
When the exception was thrown, this was the stack
#2 NavigatorState.build
package:flutter/…/widgets/navigator.dart:2330
#3 StatefulElement.build
package:flutter/…/widgets/framework.dart:4334
I have tried this but popUntil still throws the exception
try {
Navigator.popUntil(context, ModalRoute.withName('workout'));
} catch (e) {
Future.delayed(Duration(milliseconds: 1000), () {
Navigator.push(context, MaterialPageRoute(
builder: (_context) => WorkoutPage(),
settings: RouteSettings(name: 'workout'),
fullscreenDialog: true
));
});
}
If you are working on clearing the entire stack and showing a specific screen, you should try the below code:
Navigator.of(context).pushNamedAndRemoveUntil('/screen4', (Route route) => false);
It should do the work.