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

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

Related

Response body is empty in http call

I am calling a remote PHP file to get some data into my Flutter app.
This is the Flutter function:
Future<void> registrarUsuario() async {
var url = Constantes.adminUsuariosUrl + 'nuevo_usuario.php';
final response = await http.post(Uri.parse(url), body: {
"email": controllerEmail.text,
"password": controllerPass.text
});
print("response ${response.body}");
}
Calling the function the print output is empty.
flutter: response
But calling the PHP file using Postman gives me the following output:
[{"id":"57","correo":"modestovasco#gmail.com"}]
I would like to update the funtion registrarUsuario to get the json objects from the response.body
Encode the body content in request
Future<void> registrarUsuario() async {
var url = Constantes.adminUsuariosUrl + 'nuevo_usuario.php';
final response = await http.post(Uri.parse(url), body:json.encode({
"email": controllerEmail.text,
"password": controllerPass.text
}));
print("response ${response.body}");
}

how to get the values inside Instance of 'Future<Response<dynamic>?>' in 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)

Image can't be uploaded to the server in flutter using DIO

So I was trying to update my profile user by using a backend framework named ASP.NET core. It works fine when I try to use the API in the postman, it’s 100% working, it changes all of the userprofile from the email, image, and etc. But the thing is when I try to use the API in the flutter, it doesn’t work. When I try to debug it, I found that one of my variables which is in the model can’t catch the multipartfile from an image, and that makes an error.
What I have tried to solve this problem(but still doesn’t work):
I have changed the resolution
I have changed the width and height of the image
POSTMAN Is working
https://i.stack.imgur.com/lj1af.png
UserProfileServices.dart
Future<Response> updateProfile(
File profilePic,
String email,
String password,
String fullName,
String phoneNumber,
DateTime dateOfBirth,
String gender,
String address,
String city,
String province,
String postalcode
)async{
final _path="/user/update-user";
try{
FormData formData= FormData.fromMap(({
"Image": await MultipartFile.fromFile(profilePic.path,
filename: profilePic.path.split("/").last),
"Email":email,
"Password":password,
"FullName":fullName,
"DateOfBirth":dateOfBirth,
"Gender":gender,
"Address":address,
"City":city,
"province":province,
"postalcode":postalcode,
}));
Response response = await httpClient.put(_path,data:formData);
return response;
}
catch(e)
{
print(e);
return e.response;
}
}
Debugging, the profilepic variable was successfully getting the image path, but the image can't catch that
https://i.stack.imgur.com/a5AU7.png
Install and import mime and dio and http(just in case)
import 'package:dio/dio.dart';
import 'package:mime/mime.dart';
import 'package:http_parser/http_parser.dart';
Code
Future<Response> updateProfile(File profilePic,String email,String password,String fullName,String phoneNumber,DateTime dateOfBirth,String gender,String address,String city,String province,String postalcode)async{
final _path="/user/update-user";
try{
Dio dio = new Dio();
final mimeTypeData =lookupMimeType(profilePic.path, headerBytes: [0xFF, 0xD8]).split('/');
FormData formData= FormData.fromMap(({
"Image": await MultipartFile.fromFile(profilePic.path,contentType: MediaType(mimeTypeData[0], mimeTypeData[1]),
"Email":email,
"Password":password,
"FullName":fullName,
"DateOfBirth":dateOfBirth,
"Gender":gender,
"Address":address,
"City":city,
"province":province,
"postalcode":postalcode,
}));
var response = await dio.post("enter your full url for api here",data: formData);
return response;
}
catch(e)
{
print(e);
return e.response;
}
}
Note: Check formData have all values
If you don't want to use Dio you can use Multipart method without dio,you can refer the the following link
flutter-image_upload
My bad guys, there is a missing key at my profile service which is the "phonenumber"key, that makes it an 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);
}
}

Register to aqueduct backend from Flutter frontend

I'm having a bit of difficulty with registering to aqueduct backend from my Flutter frontend
Here is my code in my frontend:
Future<void> signUp(String email, String password) async {
final body = "username:$email,password:$password"; //<- return request entity could not be decoded
//final body = {"username": email, "password": password}; //<- return bad state: Cannot set the body fields of Request with content-type "application/json"
try {
final http.Response response = await http.post(
"http://localhost:8888/register",
headers: {"Content-Type": "application/json"},
body: body);
final jsonResponse = json.decode(response.body);
if (jsonResponse["error"] != null) {
throw HttpException(jsonResponse["error"]);
}
} catch (error) {
throw error;
}
}
There must be some silly mistake. I believe it is with formatting body so I tried 2 options and both throw different http exception (as in comment).
Here is an example of connecting to an Aqueduct server from a Flutter client. (This isn't really a server question, though, since the client and server are independent of each other.)
Here is an example of registering:
void _register(String email, String password) async {
Map<String, String> headers = {"Content-type": "application/json"};
final jsonString = '{"username":"$email", "password":"$password"}';
Response response = await post(YOUR_URL_HERE, headers: headers, body: jsonString);
print('${response.statusCode} ${response.body}');
}
In your example you aren't encoding the JSON correctly.
And here is another example of signing in. The class is a view model architecture that I talk about here.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class LoginViewModel extends ChangeNotifier {
String _token = '';
bool _isLoggedIn = false;
bool get isLoggedIn => _isLoggedIn;
String get token => _token;
Future onLoginPressed(String username, String password) async {
if (username.isEmpty || password.isEmpty) {
return;
}
_isLoggedIn = await _login(username, password);
notifyListeners();
}
Future<bool> _login(String username, String password) async {
var clientID = 'com.example.app';
var clientSecret = '';
var body = 'username=$username&password=$password&grant_type=password';
var clientCredentials = Base64Encoder().convert('$clientID:$clientSecret'.codeUnits);
Map<String, String> headers = {
'Content-type': 'application/x-www-form-urlencoded',
'authorization': 'Basic $clientCredentials'
};
var response = await http.post(YOUR_URL_HERE, headers: headers, body: body);
final responseBody = response.body;
if (response.statusCode != 200) {
return false;
}
final map = json.decode(responseBody);
_token = map['access_token'];
return true;
}
}