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

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

Related

Flutter: Http Status Error 403 while downloading the file

In my Flutter application, I have to download multiple files and have to store it in application storage.
For that I am using Dio and added below plugin dependencies in pubspec.yaml file :
dio: any
path_provider: any
In main.dart, I have below variables :
String uri =
'https://i.picsum.photos/id/698/200/200.jpg?hmac=EElVlYPe8BAq1Btf4bWUxP9NoQP01_e8LTUzpbdKbgY';
bool downloading = false;
where uri is the URL for an Image online.
Inside initState() method, called the downloadFile() method, which is as below :
Future<void> downloadFile() async{
Dio dio= Dio();
try{
var dir= await getApplicationDocumentsDirectory();
await dio.download(uri, "${dir.path}/myimg.jpg", onReceiveProgress: (rec,total){
setState(() {
downloading=true;
});
});
}catch(e)
{
print("Error >> "+e.toString());
}
setState(() {
downloading=false;
print("Download Completes");
});
}
But, I am getting below error :
HTTP Status Error 403
MSG_WINDOW_FOCUS_CHANGED 1 1
D/InputMethodManager(15750): startInputInner - Id : 0
I/InputMethodManager(15750): startInputInner - mService.startInputOrWindowGainedFocus
D/InputMethodManager(15750): startInputInner - Id : 0
I/flutter (15750): DioError [DioErrorType.response]: Http status error [403]
I/flutter (15750): Source stack:
I/flutter (15750): #0 DioMixin.fetch (package:dio/src/dio_mixin.dart:488:35)
I/flutter (15750): #1 DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter (15750): #2 DioForNative.download (package:dio/src/entry/dio_for_native.dart:84:24)
I/flutter (15750): #3 _MyHomePageState.downloadFile (package:downloadfiles/main.dart:82:17)
I/flutter (15750):
I/flutter (15750): Download Completes
I am getting this error while running the app in android device, I have manually given File storage permission from settings for the application.
Also updated AndroidManifest.xml file as below :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
Still am getting above error. What might causing the issue?
The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it.
This status is similar to 401, but for the 403 Forbidden status code, re-authenticating makes no difference. The access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource.
String uri =
'https://i.picsum.photos/id/698/200/200.jpg?hmac=EElVlYPe8BAq1Btf4bWUxP9NoQP01_e8LTUzpbdKbgY';
This URL Asks for authorization in headers.
So use Authorization via headers for calling API.
Like this,
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(uri,
options: Options(
headers: {"Authorization": "YOUR_AUTH_KEY HERE"},
),
"${dir.path}/myimg.jpg",
onReceiveProgress: (rec, total) {
setState(() {
downloading = true;
});
});
} catch (e) {
print("Error >> " + e.toString());
}
setState(() {
downloading = false;
print("Download Completes");
});
}

Update new version is not working in flutter

I have a flutter app which has an update button. This is used to update when new version is available in play store. It works fine until few days before. But now it is not working. It only shows a notification when user has installed the same version otherwise an error will be thrown.
> 2022-07-04 12:01:39.072 27969-28023/? E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: No element
#0 ListMixin.firstWhere (dart:collection/list.dart:167)
#1 NewVersion._getAndroidStoreVersion (package:new_version/new_version.dart:157)
<asynchronous suspension>
#2 _SettingsPageState._checkVersion (package:bnews/ui_components/pages/settings_page.dart:196)
<asynchronous suspension>
So now I cant update my app using this update button. I use new_version flutter package to update. This is the code
void _checkVersion() async {
final newVersion = NewVersion(
androidId: "com.abc.def",
);
final status = await newVersion.getVersionStatus();
newVersion.showUpdateDialog(
context: context,
versionStatus: status!,
dialogTitle: "UPDATE!!!",
dialogText: "Please update the app from " + "${status.localVersion}" + " to " + "${status.storeVersion}",
updateButtonText: "Lets update",
);
}
I think package not found problem is there. But it works fine until few days before. I have also updated new_version package but still same problem. Is this problem with playstore?
this is a bug check pub.dev new_version issues
for checking if there is a new version, I use upgrader package, just wrap the home of your materialApp and it will handle everything:
home: UpgradeAlert(
upgrader: Upgrader(
showReleaseNotes: false,
dialogStyle: UpgradeDialogStyle.cupertino,
shouldPopScope: () => true,
),
child: MyHomepage(),
),
Anyone who still face this issue can try a new package new_version_plus,you can use the same code by just changing name,its that simple

Flutter is not launching dynamic URLs that are being received as response from API

I have been trying to launch a URL insder the flutter app. I am using url_launcher but am unable to launch the URL. The URL that I am receiving is a response from an API.
If I am copying the response and sending it statically, it's working, but when passing as a dynamic variable, it always shows "Could not be launched."
Code:
checkoutCartItem() async {
var url = Uri.parse(
'');
final headers = {'Content-Type': 'application/json'};
var body = jsonEncode({
"status": 2,
"uid": SignForm.userIdGlobal,
});
final encoding = Encoding.getByName('utf-8');
Response response = await post(
url,
headers: headers,
body: body,
encoding: encoding,
);
print(response.body);
Body.url = response.body.toString();
print(Body.url);
if (await canLaunch(Body.url.toString())) {
await launch(Body.url.toString());
} else {
throw 'Could not launch $Body.url';
}
}
Flutter version: 2.2,
url_launcher: ^6.0.4
Error:
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Could not launch [TextElement: '
', LinkElement: 'https://www.bsestarmf.in/ClientOrderPayment.aspx?K4HhW6zSxVp2T2sl9n5acA+J8qCjHcdVy2hyQmgbsuje2e6rf0+sujJisssdsaBFQV1zicfCer4VQUqJtRxgRiLYXwfXKkOBj9pA5dqrlOiLEPkxgWpB0QQa36DMiHhyqCA/fP60nFus9nGlM='
print(response.body)
Gives:
https://www.bsestarmf.in/ClientOrderPayment.aspx?K4HhW6zSxVp2T2sl9n5acA+J8qCjHcdVy2hyQmgbsuje2e6rf0+sujJiBFQV1zicfCer4VQUqJtRxgRiLYXwfXKkOBj9dddddpA5dqrlOiLEPkxgWpB0QQa36DMiHhyqCA/fP60nFus9nGlM=
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Could not launch Body.url
#0 checkoutCartItem (package:optymoney/Cart/Components/Body.dart:58:5)
<asynchronous suspension>
#1 _BodyState.build.<anonymous closure>.<anonymous closure> (package:optymoney/Cart/Components/Body.dart:326:29)
<asynchronous suspension>
This is a payment link that should open a browser inside the flutter app. But it's now working.
Please help!!!
N.B: Since this is a payment link, it has been edited and so it won't work if you try launching it from a browser
final payUrl = Uri.encodeFull(response.body);
if (await canLaunch(payUrl)) {
await launch(payUrl, forceWebView: true, enableJavaScript: true);
} else {
throw 'Could not launch $payUrl';
}
This is how I resolved the issues. Turns out that encoding the received response was the solution needed.

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

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