Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Preferences in Xamarin.forms

I have tried to save login value as true if user has logged in once by using

Application.Current.Properties["isLoggedIn"] = "true";

but its not working. If i remove my app from background it again shows the login page but if user is logged in it should show the next page.

like image 699
Priyanka singhal Avatar asked Jun 17 '26 04:06

Priyanka singhal


1 Answers

When using 'Application Properties Dictionary' you have to keep in mind few things:

  • According to the official documentation: 'The Properties dictionary is saved to the device automatically'. However, if you want to ensure persistence you have to explicitly call SavePropertiesAsync().
  • The Properties dictionary can only serialize primitive types for storage. Attempting to store other types such as List can fail silently.

Read the official documentation carefully and pay attention to details.

Here is a code example:

private async Task SaveApplicationProperty<T>(string key, T value)
{
    Xamarin.Forms.Application.Current.Properties[key] = value;
    await Xamarin.Forms.Application.Current.SavePropertiesAsync();
}

private T LoadApplicationProperty<T>(string key)
{
    return (T) Xamarin.Forms.Application.Current.Properties[key];
}

// To save your property
await SaveApplicationProperty("isLoggedIn", true);

// To load your property
bool isLoggedIn = LoadApplicationProperty<bool>("isLoggedIn");

Base on your needs you may consider Local Database or Settings Plugin instead. However for saving just a few primitive values Application Properties approach should be good enough.

like image 110
EvZ Avatar answered Jun 20 '26 09:06

EvZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!