Home > Back-end >  is it possible to save the api response into sharedpreferences inside the login function?
is it possible to save the api response into sharedpreferences inside the login function?

Time:11-30

can anyone please help me?, I created a login function with api, when the user wants to login and succeeds then it is directed to the profilescreen the user details appear, but when it switches to the homescreen and switches to the profilescreen again, the user details that previously appeared are lost and become null.

I thought of using sharedpreferences to save user response data after login, but I don't know if it was saved or not

Future<LoginModels> postLogin(String email, String password) async {
var dio = Dio();
String baseurl = url;

Map<String, dynamic> data = {'email': email, 'password': password};
try {
  final response = await dio.post(
    '$baseurl/api/login',
    data: data,
    options: Options(headers: {'Content-type': 'application/json'}),
  );
  print('Respon -> ${response.data}   ${response.statusCode}');

  if (response.statusCode == 200) {
    final loginModel = LoginModels.fromJson(response.data);
    return loginModel;
  }
} catch (e) {
  print('Error di $e');
}
return LoginModels();}

i tried adding sharedpreference in the part after response.statuscode == 200 , like this

    SharedPreferences pref = await SharedPreferences.getInstance();
    String jsonUser = jsonEncode(loginModel);
    pref.setString('userDetail', jsonUser);
    print('data nih $jsonUser');

and the output is like this (from api (Respon -> {...})) and (i tried sharedpreferences (Data nih {...}))

LoginModels loginModelsFromJson(String str) => LoginModels.fromJson(
  json.decode(str),
);

String loginModelsToJson(LoginModels data) => json.encode(data.toJson());

class LoginModels {
  LoginModels({
   this.isActive,
   this.message,
   this.data,
});
  bool? isActive;
  String? message;
  Data? data;

factory LoginModels.fromJson(Map<String, dynamic> json) => LoginModels(
  isActive: json["is_active"],
  message: json["message"],
  data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
  "is_active": isActive,
  "message": message,
  "data": data?.toJson(),
  };
}
class Data {
  Data({
   this.iduser,
   this.nama,
   this.profesi,
   this.email,
   this.password,
   this.roleId,
   this.isActive,
   this.tanggalInput,
   this.modified,
 });

  String? iduser;
  String? nama;
  String? profesi;
  String? email;
  String? password;
  String? roleId;
  String? isActive;
  String? tanggalInput;
  String? modified;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
    iduser: json["iduser"],
    nama: json["nama"],
    profesi: json["profesi"],
    email: json["email"],
    password: json["password"],
    roleId: json["role_id"],
    isActive: json["is_active"],
    tanggalInput: json["tanggal_input"],
    modified: json["modified"],
  );
  Map<String, dynamic> toJson() => {
    "iduser": iduser,
    "nama": nama,
    "profesi": profesi,
    "email": email,
    "password": password,
    "role_id": roleId,
    "is_active": isActive,
    "tanggal_input": tanggalInput,
    "modified": modified,
  };
}

class User {
  String? id;
  String? nama;
  String? profesi;
  String? email;
  String? password;
  String? roleId;
  String? isActive;
  String? tanggalInput;
  String? modified;

  User();

  User.fromJson(Map<String, dynamic> json)
      : id = json["iduser"],
        nama = json['nama'],
        profesi = json['profesi'],
        email = json['email'],
        password = json['password'],
        roleId = json['role_id'],
        isActive = json['is_active'],
        tanggalInput = json['tanggal_input'],
        modified = json['modified'];



Map<String, dynamic> toJson() => {
        'id': id,
        'nama': nama,
        'profesi': profesi,
        'email': email,
        'password': password,
        'role_id': roleId,
        'is_active': isActive,
        'tanggal_input': tanggalInput,
        'modified': modified,
      };
}

if it is already stored how do I retrieve the data? or is there another alternative to solve the problem I have?

CodePudding user response:

you can use key-value for store in pref. if u want to save user's email,name,id than store it like this (note:this is example of GetX)

//to store data
var storeUserData = Get.find<SharedPreferences>();
storeUserData.setString('use_name',userName);
// to retrive data
var userName = storeUserData.getString('use_name');

set this userName to your profilescreen's text and you are done.

CodePudding user response:

While storing this in SharedPreferences call the toMap() method on the object This will return a Map<String, dynamic> representation of your current object.

Map<String, dynamic> productsMap = products.toMap();

After that Convert the object to String by using json.encode() and store it !

storedCart(productsMap){
     SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('userData', json.encode(productsMap));
}

you'll notice that when we convert our object to JSON it becomes a big String, Therefore it is possible for us to store it in SharedPreferences using the "putString()" method.

Also you can store single single value store in SharedPreferences

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("user", token);

Also When you want to get data from sharedPref you have to call

var value = prefs.getString(key);

After that you have to decode the value.

var decodeValue = json.decode(value)
final loginModel = LoginModels.fromJson(decodeValue).

after that you can find every data base on your model class

CodePudding user response:

Don't forget to use .apply() once you update the fields in the code.

  • Related