Tobias H.
Tobias H.

Reputation: 494

Flutter; save user generated data on phone

In my app I have a list that the user adds items to. I want to be able to store this data (the list) locally, on the phone, so the list can show up next time the user opens the app. How would I do that.

(the app is only for android phones)

Upvotes: 0

Views: 435

Answers (2)

Amir Hossein Mirzaei
Amir Hossein Mirzaei

Reputation: 2375

you can use the Shared Preferences plugin which is a simple key-value storage

here is the link to the plugin https://pub.dev/packages/shared_preferences/install

here is an example of how u can store a list of items and also how to load them :

class PersonData {
  final String id;
  final String name;
  final String lastName;

  PersonData({this.id, this.name, this.lastName});

}
void saveItems(List<PersonData> items) async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  List<String> personList = [];

  items.forEach((element) {
    personList.add("${element.id},${element.name},${element.lastName}");
  });

  sharedPreferences.setStringList("personData", personList);
}

Future<List<PersonData>> loadItems() async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  List<String> personList = sharedPreferences.getStringList("personData");

  List<PersonData> items = [];

  personList.forEach((element) {
    List<String> personData = element.split(",");

    PersonData person = PersonData(
        id: personData[0], name: personData[1], lastName: personData[2]);

    items.add(person);
  });
  return items;
}

Upvotes: 1

devdanetra
devdanetra

Reputation: 13

You can use different approaches,

Shared Preferences - Saving data into local cache.

Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Data may be persisted to disk asynchronously, and there is no guarantee that writes will be persisted to disk after returning, so this plugin must not be used for storing critical data.

Sqflite - Using an SQLite local database.

SQLite plugin for Flutter. Supports iOS, Android and MacOS. Support transactions and batches Automatic version managment during open Helpers for insert/query/update/delete queries DB operation executed in a background thread on iOS and Android

If it's a small app i suggest to use Hive

Hive is a lightweight and blazing fast key-value database written in pure Dart

That's an example using Hive.

var box = Hive.box('myBox');
box.put('name', 'David');
var name = box.get('name');
print('Name: $name');

Of course there are many packages that use different ways to store data, you can search for the one that fits more your usage.

Upvotes: 0

Related Questions