Home > Software design >  Flutter, how to set and get list of values in shared preferences
Flutter, how to set and get list of values in shared preferences

Time:10-22

I have SharedPreferencesHelper class where I stored simple data that I need. I came across an issue. I need to store 3-4 strings in the list in shared preferences. How can I do the setter and getter for it?

SharedPreferencesHelper class:

class SharedPreferencesHelper {
  static SharedPreferences? _preferences;

  Future<void> init() async {
    _preferences ??= await SharedPreferences.getInstance();
  }

  String get username => _preferences?.getString(keyUsername) ?? '';

  set username(String value) {
    _preferences?.setString(keyUsername, value);
  }

  // get aliases
  List<String>? get aliases => _preferences?.getStringList(keyAliases);

  // set aliases
}

CodePudding user response:

You can do this to save list of string:

var pref = await SharedPreferences.getInstance();
pref.setStringList('someList',['1','2','3']);

and get it like this:

var result = pref.getStringList('someList');
if (result != null) {
  print('result= $result'); //result= [1, 2, 3]
}

CodePudding user response:

You can write the code like that :

class SharedPreferencesService {
      SharedPreferencesServiceImpl(this.preferences);
    
      final SharedPreferences preferences;
    
      /// Static Variables
      static const _userId = 'user_id';
    
      @override
      Future<String?> get userId async => preferences.getString(_userId);
    
      @override
      Future<void> setUserId(String value) async =>
          await preferences.setString(_userId, value);
    
      @override
      Future<void> clear() async => await preferences.clear();
    }

Moreover, you have to inject SharedPreferencesInstance in your getIt (recommended to use)

final getIt = GetIt.instance;
       Future<void> setupExternals() async {
          final prefs = await SharedPreferences.getInstance();
          getIt.registerLazySingleton(() => prefs);
        
    getIt.registerLazySingleton<SharedPreferencesService>(
          getIt());
         
        }
  • Related