.NET MAUI currently have limitations of the supported types in preferences. They can only store simple data types such as strings, integers, and booleans, and do not support more complex data types such as lists or objects. This can make it difficult to store and retrieve more complex data structures.
How to store arrays and lists, or complex classes in Preferences?
The answer is currently to serialize it. Since Preferences is supporting string saving option, you can serialize your arrays and custom classes, and store the string value.
But be aware to store large amounts of data in Preferences as a string. Consider choosing SQLite to store data when there are more than 50-100 items in an array, or your class is more complex than having 25 properties. As Microsoft marks this as a limitation: Performance may be impacted if you store large amounts of text, as the API was designed to store small amounts of text.
But there are cases when it makes sense to store other types
There are cases when it is easier to store a whole complex object on disk than to store all its properties one by one by calling preferences Set. In this case you may find useful the banditoth.MAUI.PreferencesExtension.
Usage
This package is extending the basic functions of the built in MAUI Essentials IPreferences
by letting the developers to save any type of object. This is done by using JSON serialization, and saving the raw jsons as strings with the default IPreferences
implementation. Since JSON arrays can be serialized back to any collection type, you can use different types when Setting the value and when Getting it back.
There are several ways to access this extension.
Dependency Injection
private readonly IPreferences preferences;
public MainPage(IPreferences preferences)
{
InitializeComponent();
this.preferences = preferences;
}
private void Foo()
{
List<string> taleItems = new List<string>()
{
"The quick brown fox",
"Jumps over the lazy dog"
};
preferences.SetObject<List<string>>("Tale", taleItems);
string[] taleItemsFromPreferences = preferences.GetObject<string[]>("Tale", null);
}
Access through Preferences
If you are used to access the preferences trough the static class
, you can use this tool by accessing the Default
property on the Preferences
class. You can call the SetObject
or GetObject
extension method on it.
// Setting the value
Preferences.Default.SetObject<IDeviceInfo>("Device_Information", DeviceInfo.Current);
// Getting the value
Preferences.Default.GetObject<IDeviceInfo>("Device_Information", null);
Package’s own static reference
You can also access the SetObject
or GetObject
method on PreferencesExtension
static class.
// Setting the value
PreferencesExtension.SetObject<DisplayOrientation>("Last_Display_Orientation", orientation);
// Getting the value
PreferencesExtension.GetObject<DisplayOrientation>("Last_Display_Orientation", DisplayOrientation.Landscape);