how to get the values inside Instance of 'Future<Response<dynamic>?>' in Flutter? - flutter

I'm using Dio for http requests and the function for post method is like this :
Future<Response?> post(String url, dynamic data) async {
try {
Response response = await baseAPI.post(url, data: data);
return response;
} on DioError catch(e) {
throw Failure(e.message);
}
}
then when I use this post method the response I get is in Instance of 'Future<Response?>'. So how can I access the response data inside this?
void login(String email, String password) {
dynamic data = jsonEncode(<String, String>{
'email': email,
'password':password,
});
Future<Response?> response = loginService.post('https://reqres.in/api/login',data) ;
print(response);
print('response data print');
}

as your loginService.post is returning a future type, you can get the Response value by adding await in front of it, but then your login function will have be declare it as async, such as:
Future<void> login(String email, String password) async {
dynamic data = jsonEncode(<String, String>{
'email': email,
'password':password,
});
Response? response = await loginService.post('https://reqres.in/api/login',data) ;
print(response);
print('response data print');
}
Or if you do not wish to async your login function, you can add .then to your post loginService.post like below:
Response? response;
loginService.post('https://reqres.in/api/login',data).then((data) => response = data)

Related

http put did not send any response in flutter

Hey I have this app where I can update status, and I use http.put method, but it takes forever to response. I got this error
error
And here is the code for http.put
Future<void> mapEventToState(
Emitter<ReportStatusState> emit, ReportStatusEvent event) async {
emit(ReportStatusLoading());
ReportStatusPut statusPut = event.statusPutBody;
// ReportStatusModel model =
// await apiAuthRepository.updateReportStatus(statusPut, event.id);
ReportStatusModel model = await updateReportStatus({'biaya': '0', 'status': 'SELESAI'}, event.id);
print(model);
if (!model.success) {
emit(ReportStatusFailure(model.message));
}
print(model.code);
emit(ReportStatusSuccess());
}}
Future<ReportStatusModel> updateReportStatus(
Map data, String id) async {
final SharedPreferencesManager sharedPreferencesManager =
locator<SharedPreferencesManager>();
String? token =
sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessToken);
try {
final response = await http.put(
Uri.parse('https://api.komplekku.com/officer/api/report/v1/$id'),
body: json.encode(data),
headers: {'Authorization': 'Bearer $token'});
return ReportStatusModel.fromJson(json.decode(response.body));
} catch (e) {
throw Exception(e);
}
}
There is nothing wrong with the API, I already check using Postman and it worked perfectly fine, Anyone know what went wrong?

Flutter/Dart http request response with a value

I have an app which is using http request for php server.
But I have a problem here.
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get(Uri.parse('https://meshcurrent.online/get_1userdrive.php'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
I have a code like this. I am getting datas from the server. But I want to send a value to php server. and get datas depend on the value.
For instance, I will send username to the php server and I will get the datas about the username parameter. My php codes works but the problem is in flutter code.
Thanks for your helps
If youre tryting to send parameters over a get, you could use something like:
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://meshcurrent.online/get_1userdrive.php?userId=5'));
if (urlCallResponse.statusCode == 200) {
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
} else {
...
}
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Here is an example on how to do a post:
final response = await post(
Uri.parse(
'http://.../PostCall'),
headers: {
'authorization': getBasicAuth(username, password),
'Content-type': 'application/json',
'Accept': 'application/json',
},
body: json.encode(jobFormValue),
);
if (response.statusCode == 200) {
}
getBasicAuth function:
String getBasicAuth(String username, String password) {
return 'Basic ${base64Encode(utf8.encode('$username:$password'))}';
}

How to use the argument from function for body of http request with Dio package

Future<void> login(String email, String password) async {
String url = "https://phone-book-api.herokuapp.com/api/v1/signin";
Response response;
var dio = Dio();
response = await dio.post(url,
data: {"email": email, "password": password);
print(response.data);
}
if i make function with the above code i got some error, but if i fill the body with hard code, it no error happen, and i can receive the response, below the code example
Future<void> login(String email, String password) async {
String url = "https://phone-book-api.herokuapp.com/api/v1/signin";
Response response;
var dio = Dio();
response = await dio.post(url,
data: {"email": "l200140004#gmail.com", "password": "l200140004");
print(response.data);
}
anyone can help me and explaine to me about it case, please...
I am sorry All, my password input is wrong, so it can be error

how to post form data request using flutter in http package

I want to send form data in flutter using the HTTP package. Getting the error:FormatException: Unexpected character (at character 1)
I/flutter (30465):
I am sending the form data in the HTTP post request.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = 'https://yobimx.com/citykey/api/users/login';
final response = await http.post(url, body: {
'email': 'usamashafiq199#outlook.com',
'password': '123',
}, headers: {
"Content-Type": "application/x-www-form-urlencoded",
});
print(
json.decode(response.body),
);
final responseData = json.decode(response.body);
} catch (error) {
print(error);
}
}
I have to use a multipart request for request. Thanks for your help.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = Uri.parse('https://yobimx.com/citykey/api/users/login');
Map<String, String> requestBody = <String, String>{
'email': 'usamashafiq199#outlook.com',
'password': '123'
};
var request = http.MultipartRequest('POST', url)
..fields.addAll(requestBody);
var response = await request.send();
final respStr = await response.stream.bytesToString();
print(
jsonDecode(respStr),
);
print("This is the Status Code$respStr");
var encoded = json.decode(respStr);
print(encoded['status']);
print('This is the userId${encoded['data']['user_id']}');
} catch (error) {
print(error);
}
}

Http request sent an empty body

This is the code for my post request:
Future<User> createUser(String name,String username,String email,String password, String passwordConfirm, String role) async {
final response = await http.post('http.register.com',
body:jsonEncode(<String, String>{
'name': name,
'username': username,
'number': email,
'password': password,
'passwordConfirm':passwordConfirm,
'role':role,
})
);
if (response.statusCode == 200) {
return User.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load request');
}
}
The problem is once I sent it, the body goes empty to the API.How could I solve it?
_futureUser = createUser(_namecontroller.text ,_usernamecontroller.text,_email.text ,_passwordcontroller.text ,_passwordConfirmcontroller.text, _role);
I put some more codes,I think it could be helpful.
According to post function document https://pub.dev/documentation/http/latest/http/post.html
If body is String , the content-type of the request will default to "text/plain".
If body is Map , the content-type of the request will default to "application/x-www-form-urlencoded".
You can set header to application/json
code snippet
http.post(url,
headers: {"Content-Type": "application/json"},
body: body