im beginner in flutter, i want to get data form API but the API is 'post' tipe. how to retrieve the data? please help me. thank you (:
example, i have API data "post" and the data is 'phonenumber', 'password', 'address', 'name', 'class'. how to get all of the data and show/display it all?
I have a code snippet of it which you can refer
This is about calling the POST API of the student and pass the credentials as a body.
Future<Map<String, dynamic>> loginUser(String phone, String pass) async {
http.Response response = await http.post(
EndPoint.Login,
body: jsonEncode(
{
"phonenumber": phone,
"password": pass,
},
),
headers: {"Content-Type": "application/json"},
);
var parsed = jsonDecode(response.body);
Map<String, dynamic> authfailed = {};
if (parsed['message'] == "Auth failed") {
authfailed['message'] = "Auth failed";
return authfailed;
}
// print(parsed);
return parsed;
}
Related
At moment im using this snippet of code to sign in to google, but i cant get user email… anyone know how to do this?
var LoginGoogle = () => {
const [request, response, promptAsync] = Google.useAuthRequest({
androidClientId: 'xxxxxxx.apps.googleusercontent.com',
expoClientId: 'xxxxxxx.apps.googleusercontent.com'
},{
scopes: ["email"]
},{});
React.useEffect(() => {
if (response?.type === 'success') {
const { authentication } = response;
console.log(response);
}
}, [response]);
return (
<GoogleSocialButton disabled={!request} onPress={() => {promptAsync()}} />
)
}
response returns object with links instead of email
I wish this is written in the expo docs. I would like to add a few points from the first answer:
First if you need code snippets on how to fetch user data after getting the access token, you can refer to this github issue: https://github.com/expo/expo/issues/8384
access token can be received by the following code after receiving the response object:
const { authentication: { accessToken } } = response;
then, you can create a function like this:
async function fetchUserInfo(token) {
const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
});
return await response.json();
}
and get the user object (which contains the user email, profile, photo, etc) by something like this inside an async function:
const user = await fetchUserInfo(accessToken);
But NOTE for the user object, using https://www.googleapis.com/oauth2/v2/userinfo and https://www.googleapis.com/oauth2/v3/userinfo, will yield slightly different result/object ; in particular for v3, since Google implements the OpenID Connect API, there is no "id" attribute anymore, "id" will be called "sub".
sources:
How to identify a Google OAuth2 user?
https://developers.google.com/assistant/identity/google-sign-in-oauth
https://github.com/expo/expo/issues/8384
Example of a user object in v3:
Object {
"email": "xxxxx#gmail.com",
"email_verified": true,
"family_name": "John Deer",
"given_name": "John",
"hd": "gmail.com",
"locale": "en",
"name": "John Deer",
"picture": "https://lh3.googleusercontent.com/a/asdfjasdklfjaslkf",
"sub": "10998837733652322",
}
Hope this helps someone in the future...!
EDIT: if you need the id_token checkout this one:
expo-auth-session/providers/google Google.useAuthRequest
I am using AuthSession as well in my RN app and I stumbled with this problem. After going through Google API Docs, found out you can pass the access token from the useAuthRequest response to https://www.googleapis.com/oauth2/v3/userinfo?access_token= ACCESS_TOKEN.
im trying to request data from my API and to get the data, it requires a bearer token which can be obtain by log-in. and as a frontend I created a function to save and request from the UI to the API. I'm using flutter framework for the UI.
I've managed to create a function to store the bearer token generated at login, which keeps the user logged in. and it works by saving the bearer token in sharedpref.
login() async {
final response = await http.post(
"https://api.batulimee.com//v1_ship/login_app",
body: {"email": email, "password": password},
);
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
String apikey = data['data']['apikey'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('apikey', apikey);
if (status == "success") {
Navigator.of(context).pushReplacement(PageRouteBuilder(
pageBuilder: (_, __, ___) => new bottomNavBar(),
transitionDuration: Duration(milliseconds: 600),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return Opacity(
opacity: animation.value,
child: child,
);
}));
print(pesan);
print(apikey);
} else {
print(pesan);
}
}
heres the response.
{
"status": "success",
"data": {
"apikey": "UUFmb0w3WlI4Q01qOWRTamgxOFVZRjhIeWhFMkN3T205R20xZXNpYw==",
"id_user": 50,
"id_role": "8",
"name_role": "Ship Owner",
"email": "me#gmail.com",
"phone": "0210201",
"saldo": "0",
"photo": "https://cdn.batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
and now I want to create a function that can get user profile data, and where to get this data requires the bearer token which I got from login. I need this so that the user can edit their name, password, or other data in the user's profile and save it.
My backend has created the API get my_profile. which I explained earlier, to get this requires a token bearer that is the same as the token bearer we got earlier from login. And now it's my job to get the get my_profile data using a function in flutter.
heres the response from the API get my_profile.
{
"status": "success",
"data": {
"id_user": 49,
"id_role": "8",
"name_role": "Ship Owner",
"first_name": "a",
"last_name": "f",
"email": "afriansyahm86#gmail.com",
"phone": "082258785595",
"saldo": "0",
"company_name": "aa",
"company_address": "jl kav pgri",
"photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "get profile detail successfully "
}
How is the function to store the bearer token into Authorization so I can get my_profile data ? please help me.... :(
make an api class :
import 'package:http/io_client.dart';
class Api {
String _token;
final Client http =IOClient(HttpClient()
..badCertificateCallback = _certificateCheck
..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds));
static bool _certificateCheck(X509Certificate cert, String host, int port) =>
host.endsWith('EXAMPLE.com'); // Enter your url for api here
String GetToken() {
return _token;
}
Future<bool> setToken(String token) async {
_token = token;
return Future.value(true);
}
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
}
in your login use the setToken:
await _api.setToken(apikey);
next for your profile or any request in api class:
Future<ProfileResponse> getProfile() async {
var url = "$urlPrefix/api/v1/profile";
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
print(
"$response");
var parsed = json.decode(response.body);
var message = parsed["message"];
if (message != null) {
throw message;
}
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
// return the response you want
return json.decode(response.body);
}
Im a newbie to flutter so please if you think the question context is wrong update it, im fetching a data from an SQl server to my flutter app, and i also want to send the users info back to the server after they fill out a form, im using the http.post and i get the response’s body correctly but when i open the Server Url (api url) i dont see it updated with the new info i posted to it, can someone please tell me how Post is supposed to work?
I'm new to Flutter too, this is a working example of how i understand it
class HttpService {
createUser(String name, String lastname) async {
Map data = {'name': name, 'lastname': lastname};
var body = json.encode(data);
var jsonResponse = null;
var response = await http.post(serverUrl + "/create/",
headers: {
HttpHeaders.authorizationHeader: '**Token_here_if_you_use_it**',
HttpHeaders.contentTypeHeader: "application/json",
}, body: body);
jsonResponse = json.decode(response.body);
if (response.statusCode == 201) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
print(jsonResponse.toString());
}
} else {
print(jsonResponse.toString());
}
}
}
In your main.dart :
final HttpService httpService = HttpService();
httpService.createUser(name,lastname);
i want to consume a web service that require headers, body and parameters in future class
but the problem it shows an error "the named parameters isn't defined'
Future<http.Response> postLogin(String login, String password, String jwt) async{
final response = await http.post(Uri.encodeFull('$baseurl/mobile/login'),
headers: {
HttpHeaders.acceptHeader: 'application/json ; charset=utf-8',
HttpHeaders.contentTypeHeader:'application/x-www-form-urlencoded',
HttpHeaders.authorizationHeader :'Bearer $jwt',
},
body: bodyLoginToJson(login, password, token),
parameters: {
token, login
}
);
can someone help please
As mentioned by #jamesdlin, parameters is not a named parameter of the http class. The standard way of posting values using dart / flutter is a map past to the body parameter. Don't assume the terminology used in postman will be the same in dart.
Map<String, String> _headers = {
"Accept":"application/json"
};
var response = await http.post(LOGIN_URL, headers: _headers, body: {
"username": username,
"password": password,
// whatever other key values you want to post.
}).then((dynamic res) {
// ... Do something with the result.
});
I need your help. I've been follow tutorial for POST API from Login App using REST API and SQFLite , but I can't have any return after calling the request. Please correct my code below.
login_presenter.dart
doLogin(String username, String password) {
api.callAPI(username, password).then((Post user) {
_view.onLoginSuccess(user);
}).catchError((Exception error) => _view.onLoginError(error.toString()));}
rest_ds.dart
Future<User> login(String username, String password) {
return _netUtil.post(LOGIN_URL, body: {
"username": username,
"password": password
}).then((dynamic res) {
print(res.toString());
if(res["error"]) throw new Exception(res["error_msg"]);
return new User.map(res["user"]);
});
}
second tutorial I'd get from ParsingJSON-Flutter , the error Object.noSuchMethod always point at _presenter.doLogin(_username, _password); which mean I don't reach the presenter? Thanks for helping.
you should parse the JSON from response.body not the body directly.
Future<User> login(String username, String password) {
return _netUtil.post(LOGIN_URL, body: {
"username": username,
"password": password
}).then((response) {
//check response status, if response status OK
print("Response Status : $res");
if(response.statusCode == 200){
var data = json.decode(response.body);
if(data.length>0){
//Convert your JSON to Model here
}
else{
//Get Your ERROR message's here
var errorMessage = data["error_msg"];
}
}
});