0

Is there a way to store lists natively using Xamarin Forms?

b4ux1t3
  • 439
  • 1
  • 6
  • 21
asv
  • 33
  • 2
  • 7

2 Answers2

13

The Xamarin Settings plugin is obsolete and no longer maintained. Its functionality has been rolled into Xamarin.Essentials which is recommended going forward.

  1. Add the Newtonsoft.Json NuGet Package & the Xamarin.Essentials NuGet Package

  2. Utilize Newtonsoft.Json.JsonConvert to serialize/deserialize the List<T> to/from a string and save/retrieve it using Xamarin.Essentials.Preferences

using System;
using Newtonsoft.Json;
using Xamarin.Essentials;

namespace YourNamespace
{
    static class Preferences
    {
        public static List<string> SavedList
        {
            get
            {
                var savedList = Deserialize<List<string>>(Preferences.Get(nameof(SavedList), null));
                return savedList ?? new List<string>();
            }
            set
            {
                var serializedList = Serialize(value);
                Preferences.Set(nameof(SavedList), serializedList);
            }
        }

        static T Deserialize<T>(string serializedObject) => JsonConvert.DeserializeObject<T>(serializedObject);

        static string Serialize<T>(T objectToSerialize) => JsonConvert.SerializeObject(objectToSerialize);
    }
}
  1. Reference Preferences.SavedList from anywhere in your code
void AddToList(string text)
{
    var savedList = new List<string>(Preferences.SavedList);

    savedList.Add(text);

    Preferences.SavedList = savedList;
}

Kapusch
  • 287
  • 1
  • 13
Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
3

In settings Plugin you can store in a key-value fashion, so you can not directly store lists. A workaround can be, you can serialize your list into a json string, and you can store that using a key. And when you need the list back, you can get that json string using the key and deserialize it to the original format.

Aritra Das
  • 262
  • 3
  • 8