[英]Store data in dart/flutter
我正在 flutter 中编写一个待办事项列表应用程序,但每次我关闭应用程序时,我所有的待办事项都消失了,并且没有一个被存储。 每次关闭应用程序时如何阻止它们消失?
应用程序通常将数据存储在临时存储中,每次关闭应用程序时都会销毁。 为了永久保存数据,您可以使用sqflite 数据库或shared_preferences 数据库
如果你想使用 shared_preferences,你可以这样做:首先让 class 调用 StorageManager:
import 'package:shared_preferences/shared_preferences.dart';
class StorageManager {
static Future<bool> saveData(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
if (value is int) {
prefs.setInt(key, value);
return true;
} else if (value is String) {
prefs.setString(key, value);
return true;
} else if (value is bool) {
prefs.setBool(key, value);
return true;
} else {
return false;
}
}
static Future<dynamic> readData(String key) async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
dynamic obj = prefs.get(key);
return obj;
}
static Future<bool> deleteData(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.remove(key);
}
static Future<void> reloadSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
}
}
然后像这样使用它:当你想在存储中保存一些东西时,调用这个:
await StorageManager.saveData('some unique key', your int or string or bool value);
当你想从存储中读取时:
var result = await StorageManager.readData('some unique key');
if (result != null) {
// use your value
} else {
// this means there is no result
}
使用 sqlite 或文件。 请参阅食谱上的文档以了解任何一种方法。
https://docs.flutter.dev/cookbook/persistence
您的另一个选择是通过 Internet 使用外部数据库
要保留您的数据(待办事项列表),您可以
您可以使用本地数据库(如sqflite 、 sqfentity 、 shared_preferences等)来做到这一点
使用此选项,您可以启动自己的服务器或使用一些快速的无服务器解决方案,例如来自 firebase 的supabase或cloud firestore 。
我推荐hive它非常易于使用且重量轻。
除了所有其他命题,您还可以尝试 Isar,它是一个 NoSQL 本地数据库,可用于所有平台:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.