.Net MAUI : Mobile local Storage Preferences using .NET MAUI
.NET MAUI provides 4 techniques for local storage options for storing data in locally on a device, depending on the nature, structure, and size of the data. The most used following 4 ways to store the local data on mobile devices.
- Preferences
- Local File Storage
- Local Database
- Secure Storage.
The Preferences class stores preferences in the native local storage, more specifically
- For Android, in the SharedPreferences.
- For iOS, in the NSUserDefaults.
- For UWP, in the ApplicationDataContainer.
Create a new MAUI Application
You can open visual studio 2022 from your Windows or Mac machine. You must follow the below 3 steps to create a new MAUI applicationStep 1: Select Create a new project
Step 2: Search the MAUI project template or choose Project Type > MAUI from the drop-down.
Step 3: Provide the configuration Details as a project name, Location, and Solutions name.
Save Preferences
Save/ Set Preference will store simple value, preference having different key and value, preference key always string type, the value of preference must be one of the following types- Boolean
- Double
- Int32
- Single
- Int64
- String
- DateTime
Preferences.Set(“KEY”,” Value”).
Get/ Default Preferences
In this example already saved the two-preference value, in the below statement will the get the value from existing preference or if preference value is not there automatic or return the default value.Preferences.Get("Existing preferences key", Default Value);
The following code confirmed already saved preference key is available or not
Clear Preferences
Clear and remove will use for dropping the preference key and value, suppose if you are doing any log out or switching to a different user this will help to clear all the preference key and value.
Preferences.Clear();
Suppose if you want to remove a particular key preference in the mobile, you can use remove preference as like below
Preferences.Remove(“Name”);
Summary
The Preferences class is intended to store small pieces of information represented by primitive .NET types. If you need to locally save and retrieve more complex and structured data, a good option is to use a local database like SQL lite and you can refer below screen output for the preference sample application.Screen 1: Show the first screen and display the default Date Time preference value in the label
Screen 2: After clicking on Register store the user name and the latest time in the preference
Screen 3: Display the existing preference value, if the user clicks on the logout option, the preference value becomes clear.
0 Comments