How I can exit from next line code in flutter - 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,
),
);
};
},

Related

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

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

Flutter - how can i use use stream controller without reloading the stream itself

StreamController<UserModel> _controller = StreamController<UserModel>.broadcast();
getFriendsName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString("token");
var username = prefs.getString("username");
final response = await http
.post(Uri.parse("http://192.168.0.111:3000/friendNames"),
headers: {
"Content-Type": "application/json",
"authorization": "$token"
},
body: jsonEncode({"username": username}))
.then((value) => value)
.catchError((e) => print(e));
UserModel usermodel = UserModel.fromJson(json.decode(response.body));
return _controller.sink.add(usermodel);
//return usermodel;
}
i created an infinite loop that reload data every 0 second
void initState() {
Timer.periodic(Duration(seconds: 0), (_) => getFriendsName());
super.initState();
}
here is the stream builder
StreamBuilder<UserModel>( /
stream: _controller.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data!.msg == "no friends to chat with") {
return Center(child: Text("No friends found."));
} else {
return ListView.builder(
itemCount: snapshot.data!.msg.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data!.msg[index]),
subtitle:
Text("${snapshot.data!.msg1![index]}"),
leading: CircleAvatar(
backgroundColor: Colors.orange,
backgroundImage: NetworkImage(
"http://192.168.0.111:3000/getImage/${snapshot.data!.msg[index]}?v=${Random().nextInt(100)}",
),
),
onTap: () async {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
return (ChatRoom(
snapshot.data!.msg[index]));
}));
},
);
});
}
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}),
What im asking for is a way to use streambuilder and listen to changes without the need of looping the stream infinitly.
so any propositions
i solved the problem by changing Timer to Stream and adding as .asBroadcastStream()
and it should look like this
return Stream.periodic(Duration(seconds: 0))
.asyncMap((event) => getFriendsName0()).asBroadcastStream();

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

Anyway to enable 'remember me' function using sharedPreferences in flutter?

Currently, I have enabled 'keep logging in' function if the user log in once successfully. However, I still want to make a 'remember me' checkbox to save the success login information for user. Can anyone please help me with this?
Need: a checkbox that enables the user to store email and password if the user logged in once successfully.
Code is shown below:
signIn(String email, pass) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String url = ServerDetails.ip +
':' +
ServerDetails.port +
ServerDetails.api +
'login';
Map<String, String> headers = {"Content-type": "application/json"};
var data = jsonEncode({
'email': email,
'password': pass,
'token': FirebaseNotifications.fcmtoken
});
var jsonResponse = null;
var response = await http.post(url, headers: headers, body: data);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
setState(() {
_isLoading = false;
});
sharedPreferences.setString("token", jsonResponse['token']);
sharedPreferences.setString(
"token_expire_date", jsonResponse['token_expire_date']);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) => MainPage()),
(Route<dynamic> route) => false);
}
} else {
setState(() {
_isLoading = false;
});
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => MainPage()));
});
setState(() {
AlertDialog alert = AlertDialog(
title: Text("Error message"),
content: Text("Oops! The password is wrong or the email is invalid."),
actions: [
okButton,
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
});
print(response.headers);
print(response.body);
}
}
Of course, you can create a simple checkbox for remember me. In the login button, you can check if this checkbox is checked. If it is, you can set email & password in shared_preferences.
Next time, when the user comes again you can get these fields automatically from shared_preferences.
Here is an example.

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