user11348571
user11348571

Reputation:

Flutter - How to Store a List of String

I have to save data for an inventory. I organized them as a string list, how can I proceed? Reading and writing to a file does not seem to be suitable because writing will overwrite (so can’t easily update) and reading would cause the structure to be lost. Please help me!

Upvotes: 2

Views: 4794

Answers (1)

Harsh Bhikadia
Harsh Bhikadia

Reputation: 10865

  1. Add this to your package's pubspec.yaml file:
dependencies:
  shared_preferences: ^0.5.2
  1. Install it, You can install packages from the command line:
$ flutter packages get
  1. Import it, Now in your Dart code, you can use:
import 'package:shared_preferences/shared_preferences.dart';

Here is how you store and get the list of string back:

String listKey = "listKey";

void storeStringList(List<String> list) async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setStringList(listKey, list);
}

Future<List<String>> getStringList() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return await prefs.getStringList(listKey);
}

This is how you can get that list

getStringList((List<String> strList){
  //strList is the string that you stored.
});

Upvotes: 2

Related Questions