i have a getx controller where i created a register user function, but when i call it from the register ui nothing seems to happen
RxBool isLoading = false.obs;
final Uri uri = Uri.parse(url + 'register');
Future registerUser(name, email, password) async {
try {
// Register user
isLoading.value = true;
final http.Response response = await http.post(
uri,
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
}),
);
isLoading.value = false;
final res = json.decode(response.body);
if (res['success'] == true) {
print(res);
} else {
print(res);
}
} catch (e) {
print(e);
}
}
Related
List is always empty even though body has contents. I am new to flutter so bare with me if this is basic. I am wanting to get back a list of station data I am coming from a c# background so forgive me if am missing something simple the test string body has the items and can see the items when i debug
class HttpService {
final String url = "url hidden";
final String host = 'url hidden';
final String apiSegment = "api/";
// ignore: non_constant_identifier_names
void login(email, password) async {
try {
Map<String, String> body = {
'username': email,
'password': password,
};
Map<String, String> headers = {'Content-Type': 'application/json'};
final msg = jsonEncode(body);
Response response =
await post(Uri.parse("$url/Login"), headers: headers, body: msg);
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['jwtToken']);
print('Login successfully');
final prefs = await SharedPreferences.getInstance();
await prefs.setString('jwtToken', data['jwtToken']);
List<Stations> stationData = await getStationData('11');
var test = stationData;
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
List<Stations> stationData = <Stations>[];
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var body2 = body.toString();
stationData = body
.map(
(dynamic item) => Stations.fromJson(item),
)
.toList();
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
print(e.toString());
}
return stationData;
}
}
I am calling my function from the same class
List<Stations> stationData = await getStationData('11');
Data from body
Actually the problem is you are returning the data after the end of try catch.
Try this
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
final stationData = List<Stations>.from(body.map((item) => Stations.fromJson(item))); // made some changes
return stationData;
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
rethrow;
}
}
I hope this will help you
auth_service.dart
The following ArgumentError was thrown resolving an I/flutter (11774): Invalid argument(s): No host specified in URI
This my Code pleaseeeeeeeee help meeee
class AuthService {
String baseUrl = 'http://shamo-backend.buildwithangga.id/api';
Future<UserModel?> register({
required String name,
required String username,
required String email,
required String password,
}) async {
// ignore: unused_local_variable
var url = '$baseUrl/register';
var header = {'Content-Type': 'application/json'};
var body = jsonEncode({
'name': name,
'username': username,
'email': email,
'password': password,
});
var response = await http.post(
Uri(),
headers: header,
body: body,
);
print(response.body);
if (response.statusCode == 200) {
var data = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(data['user']);
// ignore: prefer_interpolation_to_compose_strings
user.token = 'Bearer ' + data['access_token'];
return user;
} else {
throw Exception('Gagal Register');
}
}
}
Iwant save like this enter image description here
Please Helpme
You are not passing any url in http.post. Replace
var response = await http.post(
Uri(),
headers: header,
body: body,
);
With
var response = await http.post(
Uri.parse(url),
headers: header,
body: body,
);
Refer this documentation for detail information
Use it like this to resove this issue
// edit this line of your code
====> var header = {'Content-Type': 'application/json'};
// with this
====> var header = {'Content-Type': 'application/json; charset=UTF-8'};
// FULL CODE
class CreateGoalModals {
Future<Add_Goal_Status> create_goal_WB(
String name,
String username,
String email,
String password,
) async {
final response = await http.post(
Uri.parse(
your_application_base_url,
),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{
'name': name,
'username': username,
'email': email,
'password': password,
},
),
);
if (response.statusCode == 201) {
print('=========> 201');
print(response.body);
} else if (response.statusCode == 200) {
print('==========> 200');
print(response.body);
// after SUCCESS
if (success_text == "success") {
print('=========> SUCCESSFULLY <===========');
} else {
print('========> SUCCESS WORD FROM SERVER IS WRONG <=========');
}
// throw Exception('SOMETHING WENT WRONG. PLEASE CHECK');
} else {
print("============> ERROR");
print(response.body);
}
}
}
This is the state when logging in to the homepage:
Future<User?> login(String nim, String password) async {
String token = await UtilSharedPreferences.getToken();
SharedPreferences pref = await SharedPreferences.getInstance();
try {
var body = {
'username': nim,
'password': password,
};
var response = await http.post(
Uri.parse('http://dev.api.app.masoemuniversity.ac.id/v1/login_mhs'),
headers: {
'Authorization': 'Bearer $token',
},
body: body,
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else {
return null;
}
} catch (e) {
print(e);
return null;
}
}
And this is when I call user data after login
Future<User> getDataMahasiswa() async {
String _token = await UtilSharedPreferences.getToken();
SharedPreferences _pref = await SharedPreferences.getInstance();
final response = await http.get(
Uri.parse(
'http://dev.api.app.masoemuniversity.ac.id/v1/auth/mhs_siakad/biodata'),
headers: {
'Authorization': 'Bearer $_token',
"Content-Type": 'application/json'
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body)['data']);
} else {
throw Exception();
}
}
And this is the response when logging in with code 200 is successful, but when getting user data the response is code 401
I/flutter (15446): 200
I/flutter (15446): {"status":"success","data":{"nim":"20265028","name":"Sukandar","id_role":"f4d4d365-dc99-4fe7-b2b7-5daddf77e127","role":"Mahasiswa","level":7,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYzZlNGE3ZmFmZTAzZDYyODdhMDM2NTg4MjNiZmE0MDZjOGI4YWQ1OGQ5MTRjZDkzMzRkYjhmZDQzYjc3MjRmYWFiZDgwY2FiNzYzZjI0YTEiLCJpYXQiOjE2NjU2NDY5MzkuNzc4NTUsIm5iZiI6MTY2NTY0NjkzOS43Nzg1NTQsImV4cCI6MTY5NzE4MjkzOS43Njg5MzQsInN1YiI6ImM4MzljNmNlLTUxZDEtNGZmYS05MmIxLWQwM2FlZTQ5MWNmMSIsInNjb3BlcyI6W119.mfag9cVCgIyojIkPuXXi7-xfnAsbWds5DYRLgSovE6u6NtAI8s3ZMYVQ0X7Bgu6IE_DfNDNSB2lap6_fvv_lx41NCSvegPLcOa57XBy9dIcQOeg-rWo8B0kYnvsG2q_g4UFCx2FEnhVeWKuhyqDfM3kkG2IB3c1rGNkx50A9_uGeofqrTkxlnuTnkRnYjcTuGOEj6laRnkWsE9_HTfu2Q7-Te66ZYqIllc4CH4OaxBwSKgd3qMPrvy8sFenah6mx7RgZ2h9cpiFmTM-bj8WP6lc-DiqSJyvde14vebBNylg6NJKX7dpV7oeRJGlVDuMK4Dqihy4wDNAx4q_vCYQticiRrUwvhuXY9AZnD6IhXbqrwb0bYZE3f6eg1voKltpBiVxx0YSQkIGze_w9ceEDpZsFHWszJ0U7O99mL763kEjnZ4MM60Xyn9YZ5iRCT2uswWtljI0rUrGBgR1QPWJ5oMEOXR4CWfSZ8m7LrPwBGB_JCo8Y9Dyn6fDM-A6YSfrbXW1BlEd7eW6I
I/flutter (15446): 401
I/flutter (15446): Unauthorized.
idk the mechanism auth in your app. may be you can try this.
after success login you got this:
I/flutter (15446): 200
I/flutter (15446): {"status":"success","data":
{"nim":"20265028","name":"Sukandar","id_role":"f4d4d365-dc99-4fe7-b2b7-
5daddf77e127","role":"Mahasiswa","level":7,"access_token":"eyJ0eXAiO.....
see, now you have an access_token. use it for get the data from server
...
final response = await http.get(
// do not use UtilSharedPreferences.getToken();
// because this token use for login, its require username and password in body
Uri.parse(
'http://dev.api.app.masoemuniversity.ac.id/v1/auth/mhs_siakad/biodata'),
headers: {
'Authorization': 'Bearer $access_token',
"Content-Type": 'application/json'
},
);
....
I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman.
And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is response.stream it's type is Bytestreem and I can not convert it to Map
My code:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here I want to print the message and the errors
}
} catch (e) {
throw e;
}
}
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}
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);
}
}