flutter: FormatException: Unexpected end of input (at character 1) - flutter

I am facing this issue when I try to log into my app.
I get this error message "flutter: FormatException: Unexpected end of input (at character 1)".
This is the const API_auth = "https://www.assofacile.it/login/wp_login.php";
Does anybody knows how to solve this issue?
Future save(BuildContext context) async {
var localUrl = LOCAL_auth;
var puclicUrl = API_auth;
try {
var response = await http.post(Uri.parse(puclicUrl),
//headers: <String, String>{'Context-Type': 'application/json;charSet=UTF-8'},
body: <String, String>{
"username": username.text,
"password": password.text,
});
// if(response.body.isNotEmpty) {
// json.decode(response.body);
// }
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
if(response.body.isNotEmpty) {
json.decode(response.body);
Navigator.push(
context, MaterialPageRoute(
builder: (context) => const HomePage(),
),
);
}
// Navigator.push(
// context, MaterialPageRoute(
// builder: (context) => const HomePage(),
// ),
// );
print("Logged in");
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}

Related

Not able to use camera resource after updating camera: ^0.10.0 takepicture() function does not working

I'm not able to use cameraControllers.takePicture after updating the CAMERA version from 0.5.8+17 to 0.10.0 in pubspec.yaml
I've attached last code.
Please correct me where I'm wrong
try {
final p = await getTemporaryDirectory();
final name = DateTime.now();
final path = "${p.path}/$name.png";
await cameraController.takePicture(path).then((value) {
if (valuetype == '1') {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => AddProfile(
imgPath: path,
fileName: "$name.png",
imagetype: "1",
)));
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyApp(
imgPath: path,
fileName: "$name.png",
))).then((erg) {
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
SystemNavigator.pop();
}
});
}
print(imgPath + 'image path');
});
} catch (e) {
showCameraException(e);
}
}
onCapture(context) async {
try {
File imageFile;
// final p = await getTemporaryDirectory();
XFile xFile = await cameraController.takePicture();
if (xFile != null) {
imageFile = File(xFile.path);
}
final name = DateTime.now();
// final path = "${imageFile.path}/$name.png";
if (imageFile != null && imageFile.existsSync()) {
if (valuetype == '1') {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => AddProfile(
imgPath: imageFile.path,
fileName: "$name.png",
imagetype: "1",
)));
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyApp(
imgPath: imageFile.path,
fileName: "$name.png",
))).then((erg) {
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
SystemNavigator.pop();
}
});
}
print(imgPath + 'image path');
} else {
print('Image file does not exist');
}
} catch (e) {
showCameraException(e);
}
}
this is worked for me

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?

How I can exit from next line code in flutter

I have a function:
onTap: () {
FunctionsClass.checkToken(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AttackDetailScreen(
idAttack:
data[index]['id'].toString())));
},
Checktoken function:
static Future<http.Response> checkToken(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var url = kUrlAPI + 'checkToken/';
var response = await http.get(Uri.encodeFull(url),
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' + prefs.getString('token'),
});
var convertDataToJson = jsonDecode(response.body);
if(convertDataToJson['code'] == 401){
Loader.hide();
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => CustomDialog(
pressedAction: () {
Navigator.of(context).pop();
},
type: 'w',
title: kWarningTitle,
description: kGenericError,
buttonText: kCloseText,
),
);
//exit for next function
}
}
I want if convertDataToJson['code'] == 401, show dialog and not execute Navigator.
Something to not execute the next method
Return a value from your checkToken function that indicates whether the navigator should push or not. For example you can return null in case of an error or simply return boolean where true means push or false means don't push (or you could return the error string and check it inside onTap if you prefer that).
Let's assume you choose to return null if the navigator shouldn't push the page, then you can do this:
onTap: () {
FunctionsClass.checkToken(context).then((value) {
if(value == null) {
return; // don't do anything
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AttackDetailScreen(idAttack: data[index]['id'].toString())));
}
}
}
Try using try/catch for unexpected error too. And 'throw' a custom error.
This is consider a good practice.
static Future<http.Response> checkToken(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var url = kUrlAPI + 'checkToken/';
try {
var response = await http.get(Uri.encodeFull(url),
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' + prefs.getString('token'),
});
var convertDataToJson = jsonDecode(response.body);
if(convertDataToJson['code'] == 401){
//exit for next function
throw Exception('some error');
}
} catch (error) {
throw error;
}
}
And use ".then" and '.catchError' while calling a Future function.
onTap: () {
FunctionsClass.checkToken(context).then((_) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AttackDetailScreen(
idAttack:
data[index]['id'].toString(),
),
),
);
}).catchError((onEroor){
Loader.hide();
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => CustomDialog(
pressedAction: () {
Navigator.of(context).pop();
},
type: 'w',
title: kWarningTitle,
description: kGenericError,
buttonText: kCloseText,
),
);
};
},

Flutter : show Dialog don't appear after login failed

I have App with login page have this function to login to server ,but when it fails to login the show Dialog did't be shown :
signup() async {
var formdata = formSignUpKey.currentState;
if (formdata.validate()) {
formdata.save();
var data = {
'username': username.text,
'password': password.text,
'email': email.text,
'nat_id': natId.text
};
var url =
"http://xxx/api/controller/users/register.php";
var response = await http.post(url, body: data);
var responsebody = jsonDecode(response.body);
if (responsebody['status'] == 'success') {
saveuser(responsebody['username'], responsebody['email']);
Navigator.of(context).pushReplacementNamed('index');
} else {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Error'),
content: Text(responsebody['status']),
actions: <Widget>[
FlatButton(
child: Text('Close!'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
));
}
}
}
I have tested it many time but never shown
I solved it after "Merym" asked to put functions inside try catch ,the code :
// Dialog error
_showDialog(context) {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Error'),
content: Text('Username or password wrong'),
actions: <Widget>[
FlatButton(
child: Text('Close me!'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
));
}
//login function
login() async {
var formdata = formLoginKey.currentState;
if (formdata.validate()) {
formdata.save();
try {
var data = {'username': username.text, 'password': password.text};
var url =
"https://technosat-iq.com/myexpect/api/controller/users/login_user.php";
var response = await http.post(url, body: data);
var responsebody = jsonDecode(response.body);
print('wooow ' + responsebody['status']);
if (responsebody['status'] == 'success') {
saveuser(responsebody['username'], responsebody['email']);
Navigator.of(context).pushReplacementNamed('index');
} else {}
} catch (err) {
print('error = $err');
_showDialog(context);
}
} else {
print('Bad');
}
}

cannot navigate form login screen to bottom_tab_screen with provider

I'm trying to navigate from login screen to the bottom tab screen but nothing happen and now i have no error
it is the main
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: UserProvider()),
ChangeNotifierProvider.value(value: AppProvider()),
],
child:MaterialApp(
key: key,
title: 'Voyager',
debugShowCheckedModeBanner: false,
theme: AppTheme.getTheme(),
routes: routes,
),
);
}
my dialog which has two cases if success or fail to login or sign up
import 'package:flutter/material.dart';
class Dialogs {
static showErrorDialog(BuildContext context,
{#required String message, #required int code}) {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Ok'),
)
],
title: Text('error $code'),
content: Text(message),
backgroundColor: Colors.white,
);
},
);
}
}
my login method and it depend on user api provider
signIn() async {
var res = await userProvider.login(
_userNameController.text, _passwordController.text);
if (res is FailedRequest) {
Dialogs.showErrorDialog(widget._context , message: res.message, code: res.code);
print('results ${res.toString()}');
} else {
print("Signing in success");
Navigator.pushReplacement(
widget._context, MaterialPageRoute(builder: (context) => BottomTabScreen()));
}
userProvider.isLoading = false;
}
and the api provider which use in the login
Future<dynamic> login(String email, String password) async {
final Map<String, dynamic> body = {'email': email, 'password': password};
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.post(Environment.userLogin,
body: json.encode(body), headers: Environment.requestHeader);
print('Completed request');
print('user login response : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
// login successful
_user = User.fromJson(res['message']);
results = true;
} else {
// login failed;
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
finally the failed request class if request not done
import 'package:flutter/foundation.dart';
class FailedRequest {
String message;
int code;
bool status;
FailedRequest({
#required this.message,
#required this.code,
#required this.status,
});
}
The Issue seems to be with the res['error'] can you verify that the field error actually exists and is not null.
At this block can you print the value of res['error']
else {
print(res['error']);
// login failed;
results =
FailedRequest(code: 400, message: res['error'], status: false);
}