Flutter - Parsing data retrieved from http POST call throughout app - json

I'm new to Flutter, but have got an API http POST call up and running and have saved the retrieved data, however I'm really struggling to access this data. I'm using Shared Preferences and I've tried to call this using a Future builder, but it doesn't seem to be working. Can anyone tell me the best way to do this?
signup(name, phone, email, password) async {
setState(() {
isLoading = true;
});
print("Calling");
Map data = {
'displayName': name,
'firstName': name,
'surname': 'test',
'givenName': 'test',
'mailNickname': name,
'streetAddress': 'test',
'accountEnabled': true,
'email': email,
'mobilePhone': '"' + phone + '"',
'passwordProfile': {
"forceChangePasswordNextSignIn": false,
"password": password,
}
};
print(data.toString());
final response = await http.post(
Uri.parse(REGISTRATION),
headers: {
"Content-Type": "application/json"
},
body: jsonEncode(data),
);
setState(() {
isLoading = false;
});
if (response.statusCode == 200) {
Map<String, dynamic> resposne = jsonDecode(response.body);
if (resposne['displayName'] != null) {
// User user = resposne['user'];
//Provider.of<UserProvider>(context, listen: false).setUser(user);
savePref(
1,
resposne['displayName'],
resposne['givenName'],
resposne['surname'],
resposne['userPrincipalName'],
resposne['mobilePhone'],
resposne['userPrincipalName'],
resposne['id']);
scaffoldMessenger.showSnackBar(
SnackBar(content: Text("Welcome ${resposne['displayName']}")));
Navigator.pushReplacementNamed(context, "/signin");
}
} else {
scaffoldMessenger.showSnackBar(SnackBar(
content: Text("Please try again!" + response.statusCode.toString())));
}
}
savePref(
int value,
String displayName,
String givenName,
String surname,
String userPrincipalName,
String mobileNumber,
String email,
String id) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setInt("value", value);
preferences.setString("displayName", displayName);
preferences.setString("givenName", givenName);
preferences.setString("surname", surname);
preferences.setString("userPrincipalName", userPrincipalName);
preferences.setString("mobileNumber", mobileNumber);
preferences.setString("email", email);
preferences.setString("id", id.toString());
}
What I'm expecting is to be able to use the user's information throughout my app, e.g. their name and email.

Related

connection problem between flutter and mysql

I'm having a problem in flutter...
I'm trying to access my database and I get this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused and changed IP addresses to my IP with 10.0.2.2:8000/api and with 127.0.0.1:8000/api.
Enter to give phpmyadmin to authorize the entry of IP.
with using Flutter laravel Php.
auth_services
class AuthServices {
static Future<http.Response> register(
String name, String email, String password) async {
Map data = {
"name": name,
"email": email,
"password": password,
};
var body = json.encode(data);
var url = Uri.parse(baseURL + '/auth/register');
http.Response response = await http.post(
url,
headers: headers,
body: body,
);
print(response.body);
return response;
}
register_screen
createAccountPressed() async {
bool emailValid = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(_email);
if (emailValid) {
http.Response response =
await AuthServices.register(_name, _email, _password);
Map responseMap = jsonDecode(response.body);
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const HomeScreen(),
));
} else {
errorSnackBar(context, responseMap.values.first[0]);
}
} else {
errorSnackBar(context, 'email not valid');
}
}
globals.dart
import 'package:flutter/material.dart';
const String baseURL = "http://192.168.100.4:8000/api/"; //emulator localhost
const Map<String, String> headers = {"Content-Type": "application/json"};
errorSnackBar(BuildContext context, String text) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(text),
duration: const Duration(seconds: 1),
));
}

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.

Flutter Change Password with sharedpreferences

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');

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;
}
}