Home > database >  When Getting Data from the API and how Saving it Into Sharepreference?
When Getting Data from the API and how Saving it Into Sharepreference?

Time:07-08

-->    JSON Response

{ "data": { "CityName": null, "DOB": "7/07/2022", "DeviceType": "0", "Email": "[email protected]", "MobileNo": "1234567891", "ProfileImage": "", "UserID": "1", "UserName": "xyz", "UserType": "3" }, "message": "Successfully login", "status": 200 }

  --->  API SERVICE

                  
 Future<Loginmodel?> login() async {
if (passwordController.text.isNotEmpty && nameController.text.isNotEmpty) {
  var response = await http.post(
      Uri.parse(
        'XYZ',
      ),
      headers: {"Content-Type": "application/json"},
      body: (jsonEncode({
        'UserName': nameController.text,
        'Password': passwordController.text,
        'DeviceToken': '',
        'DeviceType': ''
      })));
  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);

    print(data);

    print(data['data']['UserID'].toString());

    if (data['data']['UserID'] == null) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Invaild Credentials")));
    } else {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => Homescreen()));

      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Succesfully Credentials")));
    }

    // await Storage.write(key: "token", value: output["token"]);
  }
} else {
  ScaffoldMessenger.of(context)
      .showSnackBar(SnackBar(content: Text("Black Field Not Allowed")));
}

}

CodePudding user response:

I'll suggest you to use hive. Here is an article with proper guide to implement that in Hive. https://mukhtharcm.com/hive-custom-objects/

CodePudding user response:

You'll could also use SQLlite as SharedPreferances doesn't support objects

CodePudding user response:

SharedPrefernces only for primitive data not objects i advice you to use sqlite if you re familiar with sql database or Hive for NoSql

CodePudding user response:

Use String: encode data when writing and decode when reading. Something like this could work:


final prefs = await SharedPreferences.getInstance();

await prefs.setString('user', jsonEncode(data['data']));

final user = jsonDecode(prefs.getString('user'));
  • Related