简体   繁体   English

如何在 Flutter 中存储项目列表

[英]How can you store lists of Items in Flutter

How could you store something like that even when the app is closed in Flutter:即使应用程序在 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>.我想也许我可以用“sqflite”来做到这一点,这是一个颤振依赖,但我不知道如何在那里存储这个 List<Item>。 Do you have any idea?你有什么主意吗?

Btw: I need multiple of these "myList" instances.顺便说一句:我需要多个这些“myList”实例。

You can store it using sqflite, hive or shared preferences.Try to save it under flutter shared preferences .您可以使用 sqflite、 hive或共享首选项来存储它。尝试将其保存在 flutter共享首选项下 These are two methods that you can use.这是您可以使用的两种方法。

Using shared preferences 1)First create a shared preference instance使用共享首选项 1)首先创建一个共享首选项实例

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.然后保存相关的数据类型。这里你需要放一个对象列表,所以添加列表并使用jsonEncode将其转换为String。

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 2)首先使用Hive创建hive数据库。这里可以输入任意名称

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.你可以试试hive包。 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.它是一个轻量级的本地存储通道,使用 hive 是个好主意,因为它有更好的读写基准。 You can search for the tutorial for the hive.您可以搜索 hive 的教程。 or just read the documentation.或者只是阅读文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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