Release APK behaves differently than debug with type Future<dynamic> is not a subtype of FutureOr<Response> error - android

Im implementing a simple app with a login screen using bloc pattern. The app runs fine when running on debug mode on the android emulator or on my android phone from android studio. When I tried the release-apk with no changes on the code, I encounter the Future is not a subtype of FutureOr error.
Here's the method on the bloc with the logic:
void submit() async{
_loginStateController.sink.add(LoginStateLoading());
User user = User();
user.email = emailController.text;
user.password = passwordController.text;
String responseBody = await ApiClient.postUser(user, "/login").catchError( (error){
developer.log("error_while_posting_user: " + error.toString());
String errorMessage = error.toString();
if(errorMessage == "missing email" || errorMessage == "missing password"){
errorMessage = "Datos faltantes";
}
else if(errorMessage == "incorrect email or password"){
errorMessage = "Correo o contraseƱa incorrecta";
}
else{
errorMessage = "Error inesperado";
}
_loginStateController.sink.add( LoginStateError(errorMessage));
return;
});
Map<String, dynamic> responseMap = json.decode(responseBody);
Utils.saveLoginInfo(responseMap);
_loginStateController.sink.add(LoginStateReady());
}
Here's the code where the http request is being made:
static Future<String> postUser(User user, String path) async {
Map<String, String> headers = Map();
headers["content-type"] = "application/json";
Map<String, dynamic> bodyMap = user.toJson();
String body = jsonEncode(bodyMap);
try {
final response = await http.post(
API_ENDPOINT + path, headers: headers, body: body).catchError( (error) {
return Future.error(error);
}).timeout(Duration(milliseconds: 10000));
if (response == null) {
return Future.error("request error");
}
if (response.statusCode != 200) {
String errorMessage = jsonDecode(response.body)["message"];
return Future.error(errorMessage);
}
return response.body;
}
catch (Exception) {
return Future.error(Exception.toString());
}
return "";
}
I've tried flutter clean several times and still getting the error.

have you checked if you have internet permission in the AndroidManifest.xml?
Can you try adding this line in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Related

Upload image to the server with the form data in flutter

i using the ImagePicker package in the dart when i pick the image i want to upload this to the server with the form data but when i try to send this i give this error
" Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.aloteb/files/Pictures/scaled_image_picker3594752094355545880.jpg'' "
and this is my code for sending to the server
var request = http.MultipartRequest('POST', Uri.parse(url));
request.fields.addAll({
'data': '$map'
});
request.files.add(await http.MultipartFile.fromPath('image',picproviderformdate.getPAth.toString()));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
and this is my ImagePickercode
picprovider pic = Provider.of<picprovider>(context,listen: false);
File image = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 50);
setState(() {
_image = image;
});
print(_image);
pic.setpathe(_image);
can any one help me for solve this problem?
I had a similar problem a while ago, and i used the Dio dependency instead of the classical Http link.
The code is very similar, and i can gave you an example.
final File file = File("${documentDirectory.path}/picture.png");
final httpDio = dio.Dio();
final formData = dio.FormData.fromMap({
"data": "{}",
"files.image": await dio.MultipartFile.fromFile(
"${documentDirectory.path}/picture.png",
filename: "picture.png",
contentType: MediaType('image', 'png'))
});
try {
final dio.Response response = await httpDio.post(
"ApiEndpoint/avatars",
data: formData,
options: dio.Options(headers: {"Authorization": "Bearer yourTokenIfNeeded"}));
if (response.statusCode == 200) {
// Success
}
} on dio.DioError catch (e) {
if (e.response != null) {
// Error
print(e.response.data);
return;
}
}
Don't forgot to update the API endpoint and route as well as your auth authorization if you need one.

Flutter String is in Future null

I want to use a string in this function that has the phone number of the device.
I get the phone number with this:
Future<void> initMobilNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
try {
mobileNumber = await MobileNumber.mobileNumber;
_simCard = await MobileNumber.getSimCards;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
if (!mounted) return;
setState(() {
var re = RegExp(r'\+[^]*');
_mobileNumber = mobileNumber.replaceRange(0, 3, ''.replaceAll(re, '+'));
});
}
My problem is that if I want to print _mobileNumber or use it in http.get I get null or a error with "Invalid Arguments"
Future<http.Response> _fetchSampleData() async {
String s = _mobileNumber;
print(s);
return http.get('http://test.php?TestPhone=' + _mobileNumber);
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
_list = data.values.toList();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
showAlertNoInternet(context);
print('Failed to load data from server');
}
}
Where is my mistake?
The problem is that I want to call the phone number before it has even been fetched. So this always resulted in null. I fixed this by fetching the number when I start the app with all the other data I need.

Ssocket exception in AWS AppSync in flutter

I am working on flutter application with AWS AppSync in that I am using the end URL of AWS server but when I try to execute the query I am getting below error
I am working in proxy setting but is not effecting this URL it's working perfectly in native android application
SocketException: OS Error: Connection refused, errno = 111, address = XXXXXXXXXXXXX.appsync-api.ap-south-1.amazonaws.com port -43872
I have a search on google but they mention the internet permission in not added in the manifest file but after added the permission I am facing the same issue.
Below is the code on the AWS app sync execute method where I am getting the error.
Future<Map> execute({
#required String endpoint,
#required String query,
#required Map variables,
#required String accessToken,
Database cache,
CachePriority priority = CachePriority.network,
}) async {
var body = jsonEncode({"query": query, "variables": variables});
Future<Map> loadFromCache() async {
var cacheKey = getCacheKey(endpoint, body);
var data = await readCache(cache, cacheKey);
if (data != null) {
logger.fine(
'loaded from cache (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()}, cacheKey: $cacheKey)',
);
}
return data;
}
if (cache != null && priority == CachePriority.cache) {
var data = await loadFromCache();
if (data != null) return data;
}
logger.fine('POST ${endpoint.toRepr()} - ${body.toRepr()}');
http.Response response;
try {
response = await http.post(
endpoint,
headers: {
HttpHeaders.authorizationHeader: AWSaccessToken,
HttpHeaders.contentTypeHeader: ContentType.json.mimeType,
"x-api-key" :AWS_APP_SYNC_KEY,
},
body: body,
);
} catch (e) {
var shouldFallback = cache != null && priority == CachePriority.network;
if (!shouldFallback || !isNetworkError(e)) rethrow;
logger.finest('network error encountered; falling back to cache - $e');
var data = await loadFromCache();
if (data != null) {
return data;
} else {
rethrow;
}
}
if (response.statusCode != HttpStatus.ok) {
throw HttpError(response);
}
logger.fine(
'loaded from network (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()})',
);
var result = jsonDecode(response.body);
var data = result["data"];
if (cache != null) {
var cacheKey = getCacheKey(endpoint, body);
await updateCache(cache, cacheKey, data);
logger.fine(
'updated cache (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()}, cacheKey: $cacheKey)',
);
}
return data;
}
you are connecting to the wrong port, I mean the port you are connecting to from your client has no listener/server, or the port and public IP is not exposed to the internet on your server side

React native debug logging stucks

I have a link in the back-end, so I fetch a post request to that link and receive a response. When I alert that response it gives a body init and body text in which I receive datas I need. Everything is good. But..
When I enable remote debugging and console.log that response, it gives body init and body blob (and both are empty). It stucks when I eneble debugging..
Thanks for attention ))
My code:
logIn = async (username, password) => {
// alert(`username : ${username}\n password : ${password}`);
let loginFormData = new FormData();
loginFormData.append('LoginForm[username]', username);
loginFormData.append('LoginForm[password]', password);
loginFormData.append('MacAddress', '111');
loginFormData.append('loginType', 'mobile');
try {
fetch('http://192.168.2.115/araqich_client/general/default/logout', {
method: 'POST',
body: loginFormData
});
let request = fetch('http://192.168.2.115/araqich_client/general/default/login', {
method: 'POST',
body: loginFormData
});
let loginResponseJson = await request;
if (loginResponseJson && loginResponseJson != null ) {
// let loginResponse = JSON.parse(loginResponseJson._bodyInit);
alert(JSON.stringify(loginResponseJson._bodyInit));
let status = loginResponse.status;
if (status) {
let SyncFormData = new FormData();
let accessToken = loginResponse.ACCESS_TOKEN;
SyncFormData.append('ACCESS_TOKEN', accessToken);
SyncFormData.append('MacAddress', '111');
SyncFormData.append('loginType', 'mobile');
let syncRequest = fetch('http://192.168.2.115/araqich_client/mobile/defaultA/syncAndroid', {
method: 'POST',
body: SyncFormData
});
let syncResponseJson = await syncRequest;
if (syncResponseJson && syncResponseJson != null) {
let syncResponse = JSON.parse(syncResponseJson._bodyInit);
let status = syncResponse.status;
if (!status) {
alert('Sorry(( something went wrong...');
} else {
alert('Life is good)))');
}
}
} else {
alert('else1')
}
} else {
alert('else')
}
} catch (error) {
alert(error);
}
}
Instead of using console.log statements, I'd advise using your debugger.

Json error with xamarin

My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`
so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);
if (data ["success"] != null)
return (string)data ["success"];
throw new Exception ((string)data ["error"]);
}
and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));
if (!isset($users[0]))
return $this->_response(array("error" => "User not found"), 403);
$user = $users[0];
if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
$user->user_token = $token;
$u_dao->update($user);
return $this->_response(array("success" => $token));
}
return $this->_response(array("error" => "Bad login"), 403);
}
return $this->_response(array("error" => "Missing data"), 500);
}
return $this->_response(array("error" => "Wrong method"), 405);
}
and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}
and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}
and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"
and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"
i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".

Categories

Resources