show dialog when there is a problem in the internet network - flutter

I mean when I log in, but the network to the database there is a problem, an information dialog will appear that the network has a problem. I'm confused about using else if here..
_login() async {
if (formKey.currentState.validate()) {
formKey.currentState.save();
try {
final response = await UserController.login({
"username": username,
"password": password,
});
if (response != null && response["success"]) {
Http.setAccessToken(response["token"]);
return Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainActivity(),
));
} else {
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Information"),
content: Text("Your account is not registered!"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
} catch (e) {
print(e.message);
}
}
}
how do I put conditions if the network has a problem then return showDialog ??

Check out the connectivity package from the Flutter Team. https://pub.dev/packages/connectivity
You can listen for any issues in changes to your network then show a snackbar or dialogbox if disconnected.
I hope this helps.
JC

Related

Where am I wrong? The code never catch an exception while trying to createUserWithEmailAndPassword

Please direct how to catch firebase auth Exception. I have used already added emails to sign up, console shows error messages but I could not catch the error by try-catch method.
Future signUp() async {
final isValid = formKey.currentState!.validate();
if (!isValid) return;
showDialog(
context: context,
builder: (context) => const CircularProgressIndicator(
strokeWidth: 2,`enter code here`
));
try {
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text.trim(),
password: confirmPasswordController.text.trim(),
);
} on FirebaseAuthException catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text('${e.message}'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Ok'))
],
);
},
);
Here you can read about how to catch errors from firebase
ُError Handling
I have removed --- formkey.currentstate.validate().
Now its working
thank you....

flutter problem: This expression has a type of 'void' so its value can't be used

this is my flutter stripe code,
Here I want response of SetupPaymentSheetParameters and presentPaymentSheet
I want to check what king of response I am getting,
Future<void> makePayment(data) async {
print(data['clientSecret']);
try {
await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: "${data['clientSecret']}",
style: ThemeMode.dark,
))
.then((value) {});
///now finally display payment sheeet
displayPaymentSheet();
} catch (e, s) {
print('exception:$e$s');
}
}
displayPaymentSheet() async {
try {
await Stripe.instance.presentPaymentSheet(
).then((value){
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: const [
Icon(Icons.check_circle, color: Colors.green,),
Text("Payment Successfull"),
],
),
],
),
));
// ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("paid successfully")));
}).onError((error, stackTrace){
print('Error is:--->$error $stackTrace');
});
} on StripeException catch (e) {
print('Error is:---> $e');
showDialog(
context: context,
builder: (_) => const AlertDialog(
content: Text("Cancelled "),
));
} catch (e) {
print('$e');
}
}
Here I getting something like this is happening I dont know.
try this :
return type of SetupPaymentSheetParameters should be Future
change your print method to this :
print(value.toString());
hope it will help!
For help with the flutter_stripe package you'll want to reach out to the developers to get better explanations.
However, it looks like your value is actually attached to the result of initPaymentSheet, which is void. SetupPaymentSheetParameters should return json data for use with initPaymentSheet.

How to catch the purchaseCancelledError from RevenueCat in Flutter

I have a loading spinner that I would like to turn off if the user cancels the purchase using RevenueCat inside of flutter.
I have a try catch block that I use to make the purchase but the error block is never initiated because the try block is always successful.
Here is the code:
purchase(BuildContext ctx, PaymentPlanType selectedPlanType) async {
final offerings = await PurchaseApi.fetchOffers();
try {
if (selectedPlanType == PaymentPlanType.weekly) {
await PurchaseApi.purchasePackage(offerings[0].availablePackages[0]);
} else if (selectedPlanType == PaymentPlanType.monthly) {
await PurchaseApi.purchasePackage(offerings[0].availablePackages[1]);
} else if (selectedPlanType == PaymentPlanType.yearly) {
await PurchaseApi.purchasePackage(offerings[0].availablePackages[2]);
}
} on PlatformException catch (e) {
var errorCode = PurchasesErrorHelper.getErrorCode(e);
if (errorCode == PurchasesErrorCode.purchaseCancelledError) {
showDialog(
context: ctx,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text(e.toString()),
actions: [
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'))
],
);
});
}
}
}
How do I just catch that error so I can change an isLoading bool to false?

wait until showdialog is closed flutter

I am trying to get the location permissions and I want to display a message before requesting the permission. but when I run the APP it doesn't wait until I close the showdialog
Future<void> checkPermission() async {
var status = await Permission.location.status;
print(status.toString());
if (status.isUndetermined) {
await showAlertPopup(context, '',
'OK')
.then((val) {
var statuses = Permission.location.request();
print(statuses);
});
}
if (status.isDenied ||
status.isPermanentlyDenied ||
status.isRestricted ||
status.isUndetermined) {
await showAlertPopup(context, '',
'error')
.then((val) {
openAppSettings();
});
}
if (status.isGranted) {
_geoAlowed = true;
}
}
and this is my code to display the popup
showAlertPopup(BuildContext context, String title, String detail) async {
showDemoDialog({BuildContext context, Widget child}) async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return child;
});
}
return showDemoDialog(
context: context,
child: AlertDialog(
title: Text(title),
content: Text(detail),
backgroundColor: grayLight,
actions: [
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.pop(context, 'OK');
},
),
],
),
);
}
As per your question, you want to request permission when user clicks 'OK' button in dialog.
You can create a callback, that is when user clicks 'OK'
showAlertPopup(context, '','OK', (){
//Code you want to execute when user clicks 'OK'
});
And little changes in you showAlertPopup
showAlertPopup(BuildContext context, String title, String detail, Function onClick) async {
showDemoDialog({BuildContext context, Widget child}) async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return child;
});
}
return showDemoDialog(
context: context,
child: AlertDialog(
title: Text(title),
content: Text(detail),
backgroundColor: grayLight,
actions: [
FlatButton(
child: Text('OK'),
onPressed: () {
//Your callback
onClick();
Navigator.pop(context, 'OK');
},
),
],
),
);
}

Flutter: future not returned after closing alert dialog

I created a http method in Flutter like below:
Future<void> addProduct(Product product) {
const url = 'https://flutter-shop-3de16.firebaseio.com/products';
return http
.post(
url,
body: json.encode({
'title': product.title,
'description': product.description,
'imageUrl': product.imageUrl,
'price': product.price,
'isFavorite': product.isFavorite,
}),
)
.then((response) {
...
notifyListeners();
}).catchError((error) {
print(error);
throw error;
});
}
I know that my url is wrong because i want to get error.
In .catchError i throw an error and in the main page by provider i used addProduct like this:
Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct)
.catchError((error) {
return showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An error occurred!'),
content: Text('Something went wrong.'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
);
}).then((_) {
print('after catch accoured');
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
});
}
}
I catchError i got error and i show an alert dialog.After tap on Okay button i want to execute then block so i returned showDialog because it return a future.
But i do not know why
.then((_) {
print('after catch accoured');
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
});
}
No to run after alert dialog is closed?
make sure using return showDialog<Null>() instead of return showDialog()
also have a try-catch with throw error when using json.decode() inside products provider
return showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An error occurred!'),
content: Text('Something went wrong.'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
).then((value) => null);
the above then((value) => null ); will solve your problem, it would help you i think.
The then block will run after the main Future; it won't run after catchError. If you want to run a piece of code after catchError, use a whenComplete block.
Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct)
.catchError((error) {
return showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An error occurred!'),
content: Text('Something went wrong.'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
);
}).whenComplete(() { // This will run after execution
print('after catch accoured');
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
});
}
}
Below code should solve your issue. moving then statement after show dialog would make it work again.
Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct)
.catchError((error) {
return showDialog(
context: context,
builder: (ctx) =>
AlertDialog(
title: Text('An error occurred!'),
content: Text('Something went wrong.'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
).then((_) {
print('after catch accoured');
setState(() {
isLoading = false;
});
Navigator.of(context).pop();
});;
});