How to handle "Lost connection to device." error - flutter

I created an app, which contains login and dashboard screen, i used Nodejs backend and mongodb also. i trying to add functionality when user logged in and close the app without logging out and then when user come to the app it should display where it left last time. so i used shared preference for it. I am testing it now, when i logged in and close the app using the right-most button (which shows all the currently running apps) it send me this "Lost connection to device.
".
login Code:
bool newuser;
String type ;
SharedPreferences myPrefs;
void initState() {
checkIfLoggedinalready();
}
Future login() async {
try {
Dio dio = new Dio();
var data = {
'username':"Munib khatri",
'password': "Munib123",
'date': "5/5/2021"
};
await dio
.post(localhostUrlLogin, data: json.encode(data))
.then((onResponse) async {
type = onResponse.data['User']['Type'];
if (type == 'Employee') {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Employee()));
} else if (type == 'Manager') {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Manager()));
}
myPrefs.setBool('login', false);
});
} catch (e) {
}
}
void checkIfLoggedinalready() async{
myPrefs = await SharedPreferences.getInstance();
newuser = (myPrefs.getBool('login') ?? true);
print(newuser);
if (newuser == false && type == 'Employee') {
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => Employee()));
}
}
dashboard code:
i am doing this on drawer code where i use logout
new ListTile(
title: new Text('Log out'),
leading: Icon(Icons.logout,color:Colors.grey),
onTap: (){
myPrefs.setBool('login', true); //here i set it to true, if user is new
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=>
Login()
)
);
},
),
please help it would be appreciated.

Lost connection to device is not a coding issue, your linked device got disconnected at that time due to data cable, If you will test this on emulator then you will not get this issue.
If you are saving user data on Shared preference then do encode your sensitive data before saving it.

var response =
await http.post(Uri.parse(parseUse), body: json.encode(data), headers: { "Content-Type": "application/json; charset=UTF-8", }).timeout(Duration(minutes: 2));
Updated Answer :
try{
Dio dio = new Dio();
var data = {
'username':"Munib khatri",
'password': "Munib123",
'date': "5/5/2021"
};
await dio
.post(localhostUrlLogin, data: json.encode(data))
.then((onResponse) async {
type = onResponse.data['User']['Type'];
if (type == 'Employee') {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Employee()));
} else if (type == 'Manager') {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Manager()));
}
myPrefs.setBool('login', false);
});
}on DioError catch (e){
if(e.type == DioErrorType.connectTimeout){
"You can put a alert dialog or something you prefer".
}
}
or you can also use base Option since your using DIO
var dio = Dio(); // with default Options
// Set default configs
dio.options.baseUrl = 'https://www.xx.com/api';
dio.options.connectTimeout = 5000; //5s
dio.options.receiveTimeout = 3000;
// or new Dio with a BaseOptions instance.
var options = BaseOptions(
baseUrl: 'https://www.xx.com/api',
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = Dio(options);
response = await dio.request(
'/test',
data: {'id':12,'name':'xx'},
options: Options(method:'GET'),
);

Related

quality of the image uploaded using multipart request is too low.how to solve this problem. thanks in advance

when i upload images to API using multipart request in flutter.the quality of the image become very unclear.iam using image_picker package to pick image from gallery.is there any way to increase the quality or maintain the same quality of my original image
iam sharing a screen shot below
iam using provider state management,here is my code
addFundImageReq ({
required BuildContext context,
required String amount,
required File image
})async{
var urls = '$reqUrl/addFundRequest';
final shareProv = Provider.of<SharedController>(context, listen: false);
var headers = {
'Authorization': 'Bearer ${shareProv.userToken}',
// "Content-Type":"multipart/form-data"
};
// /working -------
var request =
http.MultipartRequest('POST', Uri.parse(urls));
// request.fields['amount'] = amount;
request.fields['amount'] = amount;
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
contentType: MediaType('image','jpg')
)
);
// request.files.add( await http.MultipartFile.fromPath('image', image));
request.headers.addAll(headers);
http.StreamedResponse res = await request.send();
notifyListeners();
if (res.statusCode == 200) {
print(await res.stream.bytesToString());
log(image.path);
log('api workrd');
notifyListeners();
}else{
print(res.statusCode);
print(res.stream.bytesToString());
notifyListeners();
}
}
this is how i call the function in UI
Consumer<AddFundController>(
builder: (context, value, child) => CustomButton(
text: 'Continue',
onTapped: () {
value.addFundImageReq(context: context,
amount: amount,
image:imageProv.imageFile!);
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => const UploadImageScreen(),
// ));
}),

Save basic authentication value on shared preferences so on auto login data is fetched

So i in the fetching of data I have basic auth, so for the first time that the user logs in I need to take the basic authentication like value which is normally like : Basic (then some numbers), so I need to take that and store that inside the local storage. T
he reason why I need to do this is that the next screen after login is going to be a screen where data is being fetched, so I need to save the basic auth token inside the local storage so when the user closes the app and comes back I can pass the basic auth token and get the data from the API.
On the app the authorization is from the response. statusCode, so in order to get data from API I need. So what I require is for the first time the first screen will be the login screen, when the user successfully logs in, we need to get the basic auth token save it on local storage, then use that same token on basic auth, so the data is returned to the other screen successfully, and in 'authorization': basicAuth.toString(), we can do like boolVariable ? prefs.getString('keyName') : basicAuth.toString().
Any help would be really appreciated, and when you guys explain implementation of the code would be even better.
// dataset_Working_Location.dart
late Response response2;
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
String? basicAuth;
Future<Response> fetchWorkingLocationData() async {
var url = 'https://dev.api.wurk.skyver.co/api/locations';
basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${emailController.text}:${passwordController.text}'),
);
response2 = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth.toString()},
);
return response2;
}
//dataset_employees.dart
late Response response1;
Future<Response> fetchAccountData() async {
var url = 'https://dev.api.wurk.skyver.co/api/v1/employees/account';
response1 = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth.toString()},
);
return response1;
}
//login submit button
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
setState(() {
loading = true;
});
Future<Response> futureResponse = fetchWorkingLocationData();
futureResponse
.then((response) => {
if (response.statusCode == 200)
{
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page1()),
)
}
else
{
setState(() {
try {
loading = false;
} on Exception catch (e, s) {
loading = true;
}
}),
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blue,
content: Text(
"Incorrect phone number or password",
style: TextStyle(fontSize: 18),
),
duration: Duration(seconds: 4),
),
),
},
})
.catchError((error, stackTrace) => print('shush'));
}
fetchAccountData();
},
Have you considered storing values in DevicePreferences? This is a simple process (irrespective of your decision to persist information on disk/files).

Flutter field has not been initialized

i have a bool that i set to true if the account datas is right but my bool is set to late and it doesnt works
My Model:
bool _result = false;
Future login(String username, String password) async {
var url = "http://192.168.178.75/flutterconn/login.php";
var response = await http.post(Uri.parse(url), body: {
"username": username,
"password": password,
});
var data = await json.decode(response.body);
if (data == "success") {
setResult(true);
Fluttertoast.showToast(msg: "Erfolgreich Eingeloggt",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.CENTER,fontSize: 16.0);
}else {
Fluttertoast.showToast(msg: "Nicht Eingeloggt",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.CENTER,fontSize: 16.0);
}
//print(_result);
notifyListeners();
}
Future setResult(bool rs) async{
_result = await rs;
notifyListeners();
}
bool getResult(){
return _result;
}
My onPressed Method:
context.read<LoginModel>().login(
usernameController.text, passwordController.text);
print(context.read<LoginModel>().getResult());
if (context.read<LoginModel>().getResult()) {
context.read<FoodSelectionModel>().loadGalleryLinks();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FoodSelectionScreen()),
);
}
My Error:
The following LateError was thrown while handling a gesture:
LateInitializationError: Field '_result#21188420' has not been initialized.
The Bool is turned to late to true how can i set it faster.
i tried with putting async on my onPressed method and await it works thank you guys.
onPressed: () async {
await context.read<LoginModel>().login(
usernameController.text, passwordController.text);
print(context.read<LoginModel>().getResult());
if (context.read<LoginModel>().getResult()) {
context.read<FoodSelectionModel>().loadGalleryLinks();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FoodSelectionScreen()),
);
}

Error while logging in (on the server) in the flutter application

I have an application that has a piece of code that is responsible for authorization. I sent the encrypted data to the server, the data on the server will be checked, if everything is fine with the data, then I return the code 200 and additional data. I tested this code on the server without protection (http). But now when I started debugging this application with a server that has a certificate (https) I had a problem. Maybe someone knows how to solve this problem? Here is the problem code:
E/flutter (23247): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error:
E/flutter (23247): CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:354))
Here is my code:
signIn(String login, pass) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var AESLogin = login;
var AESpass = pass;
//generate a 16-byte random key
var key = '33CC2E0DD531B761316FE1231231211';
print(key);
//encrypt
var encryptLogin = await FlutterAesEcbPkcs5.encryptString(AESLogin, key);
var encryptPass = await FlutterAesEcbPkcs5.encryptString(AESpass, key);
var jsonResponse = null;
var response = await http.post(
global.urlVar + "/auth_user", body: json.encode(
{
"login": encryptLogin,
"pass": encryptPass
}),
);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
print('Response body: ${response.body}');
if (jsonResponse['message'] ==
'200') { //if( jsonResponse['message'] == '200') {
setState(() {
_isLoading = false;
});
global.nameUser = jsonResponse['name'];
global.dataArea = jsonResponse['data_area'];
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}
else {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Error_Auth()),
);
}
}
else {
setState(() {
_isLoading = false;
});
print(response.body);
}
}

Store multiple values in shared preference in flutter failed

Basically i am creating an online product app, when ever a user select any product and click on checkout button it checks whether user the is login or not. Here i did the same thing, i select a product and went cart page and clicks on checkout button (Here i am not loggedin) so it went to login page and saved the variables and then i go to the cart page and click on checkout button again it goes to login page. I have already saved the variables in login page but why it is not verifying.
Loginpage.dart
Future<UserRegister> getLogin(UserLogin userLogin) async{
final String apiUrl="http://cashback.us-east-2.elasticbeanstalk.com/user/login";
var userLoginJson = userLogin.toJson();
final response=await http.post(apiUrl,body: json.encode(userLoginJson),headers: {"content-type" : "application/json",
"Accept": "application/json",}
);
print(response);
if(response.statusCode >= 200 && response.statusCode < 300){
final responseString=response.body;
print(responseString);
var result = userRegisterFromJson(responseString);
print(result.user.userId);
print(result.user.name);
print(result.user.token);
print(result.user.mobile);
print(result.user.isDriver);
print(result.driver.driverId);
prefs.setBool('login', true);
prefs.setString('userid', result.user.userId.toString());
prefs.setString('name', result.user.name);
prefs.setString('mobile', result.user.mobile); //Here i am storing the values
prefs.setString('isDriver', result.user.isDriver.toString());
prefs.setString('driverId', result.driver.driverId.toString());
prefs.setString('token', result.user.token);
return result;
}else{
final responseString=response.body;
var result = json.decode(responseString);
print(result);
return null;
}
}
RaisedButton(
onPressed(){
getLogin(login);
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => MainPage()));
}
)
Cartpage.dart
SharedPreferences logindata;
bool newuser;
PlatformButton(
onPressed: (){
check_if_already_login();
},
child: Text('Checkout',style: TextStyle(color: Colors.white),),
androidFlat: (_) =>
MaterialFlatButtonData(color: Colors.cyan),
ios: (_) =>
CupertinoButtonData(color: Colors.cyan)
),
Future<void> check_if_already_login() async {
logindata = await SharedPreferences.getInstance();
newuser = (logindata.getBool('login') ?? true);
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => Login()));
if (newuser == false) {
print(false);
}
}
Because you put Navigator.pushReplacement before if statement
So it will directly go to Login page
You can move Navigator.pushReplacement inside if
You can change from
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => Login()));
if (newuser == false) {
to
if (newuser == false) {
Navigator.pushReplacement(
context, new MaterialPageRoute(builder: (context) => Login()));
print(false);
}