Flutter Change Password with sharedpreferences - mysql

Good day i just want to ask how do i get the sharepreferences id so i be able to change my password
class _ChangePasswordState extends State<ChangePassword> {
String c1, password, c3;
final _key = new GlobalKey<FormState>();
//i want to know how to get the id cause i got undefined id
save() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
SharedPreferences preferences = await _prefs;
String id = preferences.getString("id");
debugPrint(id);
final response =
await http.post('http://192.168.1.9/vessellog/changepass.php',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'id': id,
'password': password,
}));
debugPrint(response.body);
final data = jsonDecode(response.body);
int value = data['value'];
if (value == 1) {
} else {
}

You need to set the value of id first.
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('id','value you want');

Related

Create POST request with Int key value, status code returns 422 or 415

At first, I was confused about sending an integer value to the key id. Then an error will appear type 'int' is not a subtype of type 'String' in type cast.
After a long time of fixing it, I finally managed to fix the previous error with a code like the following:
class UserData with ChangeNotifier {
Map<String, dynamic> _map = {};
bool _error = false;
String _errorMessage = '';
Map<String, dynamic> get map => _map;
bool get error => _error;
String get errorMessage => _errorMessage;
Future<void> get fetchData async {
final Map<String, dynamic> userBody = {
'id': 1,
'username': 'bunn1est',
};
String _body = jsonEncode(userBody);
final response = await http.post(
Uri.parse('https://*******'),
headers: {
"Accept": "application/json",
"content-type": "application/json",
},
body: _body,
);
if (response.statusCode <= 1000) {
try {
_map = jsonDecode(response.body);
_error = false;
} catch (e) {
_error = true;
_errorMessage = e.toString();
_map = {};
}
} else {
_error = true;
_errorMessage = "Error: It would be your internet connection";
_map = {};
}
notifyListeners();
}
void initialValues() {
_map = {};
_error = false;
_errorMessage = "";
notifyListeners();
}
}
The above code works fine, but I get the status code 422 instead. And then I get the error status code 415 if I try to remove headers inside http.post
headers: {
"Accept": "application/json",
"content-type": "application/json",
},
Is there something wrong with my class model, or is the error happening because it's from the server-side?
If the error status code 422 shows because of my code error, which part should I fix?
EDIT
I've tried it on postman, and it works fine. I still haven't figured out how to store the key value with the Integer data type
Just modify this code
final Map<String, dynamic> userBody = {
'id': 1,
'username': 'bunn1est',
};
String _body = jsonEncode(userBody);
with this
int id = 1;
final _body = {
'id': id.toString(),
'username': 'bunn1est',
};

Flutter Registration with API

I successfully can login with my API connection also can display the data in my app.
I follow the same method for the registration to send data in API So that I can login.
But the registration is not happening, although it didn't show any error. My SnackBar showing You are already registered . But When I try to login with the data which I provided in registration form, its showing user not found( Obvious reason registration process didn't perform). Is there any problem with my API MODEL?
Here is my Parameters
{
"Email":"qwer#gmail.com",
"Mobile":"1237891",
"Password":"9991",
"RetypePassword":"9991"
}
And here is the Json response
{
"Status": "1",
"Message": "You are registered successfully",
"UserData": {
"Name": "qwer#gmail.com",
"EncUserId": "IS0QOCrLby8Ft1kbkzn/mg=="
}
}
After that I created a registration form, when user click the Register button it's run my API function registrationOfuser()
Future <void> registrationOfuser(String email, contact, pass,conpass) async{
var jsonResponse ;
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'http://myurl/home/djkjkfjkjfwkjfkwjkjfkjwjfkwjfkwf';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content:Text(" ${jsonResponse['Message']}"))) ;
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
And here is my MODEL
class RegistrationApiResponse {
RegistrationApiResponse({
required this.status,
required this.message,
required this.userData,
});
String status;
String message;
//UserData userData;
UserData? userData;
factory RegistrationApiResponse.fromJson(Map<String, dynamic> json) => RegistrationApiResponse(
status: json["Status"],
message: json["Message"],
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>),
}
class UserData {
UserData({
required this.name,
required this.encUserId,
});
String name;
String encUserId;
factory UserData.fromJson(Map<String, dynamic> json) => UserData(
name: json["Name"],
encUserId: json["EncUserId"],
);
}
Try to below code help:
Create TextEditingController
final TextEditingController email = new TextEditingController();
final TextEditingController contact = new TextEditingController();
final TextEditingController password = new TextEditingController();
final TextEditingController conpassword = new TextEditingController();
Create one function for registration
register(String email, contact, pass,conpass) async {
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'Your url here';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
Create Button
ElevatedButton(
child:Text('Register'),
onPressed:(){
register(email.text, contact.text, password.text, conpassword.text);
},
),
You need to get text from controller. Do as follows:
body:({
'Email':emailController.text,
'Mobile':phoneController.text,
'Password':passwordController.text,
'RetypePassword':rePasswordController.text,
}));
class ApiService {
callloginapi(
var email,
) async {
LoginReg? userModel;
Response response = await post(
Uri.parse('http://13.127.138.139/api/Login_Register_User'),
body: {
'mobile': email,
});
var jsonResponse = jsonDecode(response.body.toString());
userModel = LoginReg.fromJson(jsonResponse);
print(jsonResponse['token']);
var flag = jsonResponse['data']['flag'];
log('==========flag ===========$flag');
//return userModel;
var message = jsonResponse['message'];
if (response.statusCode == 200) {
if (flag == 'true') {
Get.offAllNamed(PageRoutes.home);
// t
emailController.clear();
print('$message');
// moveToHome(context);
} else {
// server error
print('Not Register');
}
}
}}

How to map the jsonDecode return with User Class in flutter

Future<Map<String, dynamic>> getUserDetails(String accessToken) async {
final url = 'https://$AUTH0_DOMAIN/userinfo';
final response = await http.get(
url,
headers: {'Authorization': 'Bearer $accessToken'},
);
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to get user details');
}
}
How can I get this return value jsonDecode(response.body) to Map with the User class so I can access the name and email in another dart file.
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() => {
'name': name,
'email': email,
};
}
The getUserDetails is in auth.dart file, the User class is in another dart file and I have to access name and email in another dart file. PLease help.
Just call first the request like that:
var response = await ClassAuth().getUserDetails(token);
And then parse data to user object:
User user = User.fromJson(response);
String email = user.email;
You can use the Provider package to solve this problem.
You can put your value and then get it from a child widget of auth provider.

How to pass nested Json into my http API in Dart

I need to pass json data into my http APIs. I am not able to find the right way to do this yet. Here's my code snippet:
For all interactions to/from API, I have created an Dbhelper class.
Here's my Dbhelper class
class Dbhelper {
String fbody; // json parameter
Map result; // Response json for the api called
Dbhelper({this.fbody});
Future<void> executeData() async {
try {
//Make post request
Response response = await post('http://<my domain>/api/GetInfo',headers: {"content-type":"application/json"},body: $fbody);
var deviceinfo = jsonDecode(response.body);
print('In dbhelper $deviceinfo');
result = deviceinfo;
} catch(e) {
print('Something occured $e');
result = null;
}
}
}
This is what i am trying to do. I have login class which takes input from UI - UserName and password and need to pass this into Dbhelper object.
the intended json to be passed in my API is :
{
"strjson":{ "cUserName":"sandy" , "cPassword":"12345" },
"strSPName":"App_Userlogin"
}
toMap(String u, String p ){
return {
"strSPName":"App_userregister",
"strjson":{
"cUserName":u,
"cPassword":p
}
};
}
void _checkLogin(String u , String p) async {
try {
Map inputs = toMap(u,p);
print(inputs);
Dbhelper db = Dbhelper(fbody: inputs);
await db.executeData();
User user = User.fromJson(db.result);
if (user.uid >0)
Navigator.of(context).pushReplacementNamed('home');
else
print("User not found");
}catch(e){
print(e.toString());
User user = User(uid:0,username:'',userbalance: 0);
}
}
Please help me what I am missing in this
While passing body to http.post request . Try passing body inside single quotes.
Response response = await post('http://<my domain>/api/GetInfo',headers: {"content-type":"application/json"},body: '$fbody');
If this doesn't work, you can try encoding your body in json format using jsonEncode as shown
body: jsonEncode(<String, String> {'uname':'SomeName',})
Hope this works!
Json that I have posted in body..
{
"user": {
"UserName": "username",
"password": "password",
"Name": "name",
"Email": "email"
}
}
Your Post Api call be like:
Future<User> postUser(String username, String password, String name, String
email) async {
Paste your api url here
String url = '';
final response = await http.post(apiUrl, headers: {
// Enter your headers parameter if needed
// E.g:
'Authorization' : 'xyz',
'Content-Type' : 'application/json'
},
body: jsonEncode(<String, String>{
'UserName' : username,
'password' : password,
'Name' : name,
'Email' : email
}));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to post user.');
}
}
Your model be like:
class User {
User? user;
User({this.user});
User.fromJson(Map<String, dynamic> json) {
user = json['user'] != null ? new User.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user != null) {
data['user'] = this.user!.toJson();
}
return data;
}
}
class User {
String? userName;
String? password;
String? name;
String? email;
User({this.userName, this.password, this.name, this.email});
User.fromJson(Map<String, dynamic> json) {
userName = json['UserName'];
password = json['password'];
name = json['Name'];
email = json['Email'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['UserName'] = this.userName;
data['password'] = this.password;
data['Name'] = this.name;
data['Email'] = this.email;
return data;
}
}

Creating flutter Json Login form with user Basic authentication

Have been stuck for quite a while on this step. can someone show me how to send a request such that upon pressing the "login" button a new instance of a user with Basic authentication is created. i would love to understand how to know how the headers are arranged to access the url database
void Login() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
makePost();
}
}
second part my json methond
Future<Post> makePost() async {
String Username = "denisPos";
String Password = "moV4b90WqpHfghghsg";
final response = await http.post('http://.60.4546.109:4520/postRequest',
headers: {HttpHeaders.authorizationHeader: '$Password:$Username:$url'});
final responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
class Post {
final String phone;
final String password;
final String body;
Post({this.phone, this.password, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
phone: json['phone'],
password: json['password'],
body: json['body'],
);
}
}
If you are talking about Basic authentication you can have something like the following code:
Future<Post> makePost() async {
String username = "denisPos";
String password = "moV4b90WqpHfghghsg";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Accept": "application/json",
"Authorization": "Basic $credentials"
};
var url = ...
var requestBody = ....
http.Response response = await http.post(url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
If you are sending a GET request you can omit the requestBody altogether.
http.Response response = await http.get(url, headers: headers);
Future<http.Response> post() async {
var url = 'http://xxxxxxxxxxxxx;
String password = "xxxxxxxxxxxxxxxx;
String username = "
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var requestBody = jsonEncode({ 'phone': phone, 'pass': pass});
http.Response response = await http.post(
url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
print(Utf8Codec().decode(response.bodyBytes));
print("Body: " + responseJson);
}