简体   繁体   中英

How can you store lists of Items in Flutter

How could you store something like that even when the app is closed in Flutter:

Class myList {
    String id;
    List<Item> list;
}

Class Item{
    //Many property’s
}

I thought maybe I could do that with "sqflite", a flutter dependency, but I have no Idea how I could store there this List<Item>. Do you have any idea?

Btw: I need multiple of these "myList" instances.

You can store it using sqflite, hive or shared preferences.Try to save it under flutter shared preferences . These are two methods that you can use.

Using shared preferences 1)First create a shared preference instance

SharedPreferences prefs = await SharedPreferences.getInstance();

Then save the relevant data type.here you need to put a object list so add the list and convert it to the String using jsonEncode.

Map<String,List<Item>> map={mylist.id: mylist.list};
prefs.setString("itemList", json.encode(map));

Then you can retrieve data like this

Map<String,List<Item>> map=json.decode(prefs.getString("itemList")).asMap();

2)Using Hive First Create the hive databse.you can put any name here

var box = Hive.box('myBox');

Then add the object in to that database

var myList = myList()
..id = your id here
..list = add list here;

var name = box.add(myList);

You can get anywhere this data list.

print(box.getAt(0));

You can try hive package. It is a lightweight local storage passage and it is a good idea to use hive because it has better benchmarks for reading and writes. You can search for the tutorial for the hive. or just read the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM