简体   繁体   中英

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.

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.

First we set the key and value using below code

Xamarin.Essentials.Preferences.Set("UserId", content.userId);

We can get the above value in any page of project using below code

Xamarin.Essentials.Preferences.Get("UserId", "");

Xamarin Forms now includes Xamarin Forms Essentials and contains the Preferences component that you need. Check out the official website and try it. https://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=ios

This is an example of how to manage preferences with Essentials.

  • To save a value for a given key in preferences:

    Preferences.Set("my_key", "my_value");

  • To retrieve a value from preferences or a default if not set:

    var myValue = Preferences.Get("my_key", "default_value");

  • To remove the key from preferences:

    Preferences.Remove("my_key");

  • To remove all preferences:

    Preferences.Clear();

Supported Data Types:

  • bool

  • double

  • int

  • float

  • long

  • string

  • DateTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM