android - Flutter 从 GetStorage 列表中获取数据值
问题描述
我想从 GetStorage() 获取数据,
我有一个商店列表,我可以将它用作仅页面的静态,这样我将我的列表保存在 GetStorage 中,如果我转到另一个也会显示的页面。就像一个 SharedPreferences。我如何显示来自 GetStorage List Value 的数据,例如
Text(basket[name]),将仅显示名称,Text(basket[price]),将仅显示价格,
var basketsd = GetStorage("totalList");
我的商店产品模型,
class PriceModel2 {
final String name;
final double price;
PriceModel2({
this.name,
this.price,
});
}
它也不起作用。
Text(controller.basketsd.read(["name"])
Container(
height: Get.size.height * 0.3,
child: Obx(() => ListView.builder(
itemCount: controller.basket.length,
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
SizedBox(
height: 20,
),
Container(
width: Get.size.width,
child: ElevatedButton(
onPressed: () {
controller.basket
.remove(controller.basket[index]);
},
child: (Text(controller.basketsd.read(["name"]) +
" " +
controller.basket[index].price.toString() +
" €"))),
),
SizedBox(
height: 20,
),
],
);
})),
),
代码显示如下(https://prnt.sc/1fs6mbf)
解决方案
这里有几个问题。至少从您共享的内容来看,您从来没有真正PriceModel2
正确地存储您的对象。如果您尝试存储一个随机的自定义对象,GetStorage
将不知道如何处理它。(SharedPreferences
在相同的情况下也不会)。
因此,对于初学者,您可以实现一个toMap
函数,将其转换为GetStorage
可以读取的地图。
将此添加到您的PriceModel2
课程中。
Map<String, dynamic> toMap() {
return {
'name': name,
'price': price,
};
}
然后在同一个类中添加一个命名构造函数,以便您可以从Map
存储的对象中创建对象。
PriceModel2.fromMap(Map map)
: name = map['name'],
price = map['price'];
我还建议,无论您使用哪个存储库,都保留所有与存储相关的功能,包括boxes
在本例中,在它自己的类中存储和返回您需要的任何数据。这样,如果您需要升级到Hive
,ObjectBox
等等……您可以在一个班级中进行,而不是在您的整个应用程序中进行。
一个例子看起来像这样。
class Database extends GetxController {
final box = GetStorage();
Future<void> initStorage() async {
await GetStorage.init();
}
void storePriceModel(PriceModel2 model) {
box.write('model', model.toMap());
}
PriceModel2 restoreModel() {
final map = box.read('model') ?? {};
return PriceModel2.fromMap(map);
}
}
然后你将在 main.xml 中初始化你的控制器和存储。
void main() async {
await Get.put(Database()).initStorage();
runApp(MyApp());
}
存储模型的示例如下所示。
ElevatedButton(
onPressed: () {
final model = PriceModel2(name: 'test name', price: 23.0);
Get.find<Database>().storePriceModel(model);
},
child: Text('Store Model'),
),
并且可以像这样在 UI 中显示存储数据。
Text(Get.find<Database>().restoreModel().name)
您不需要Obx
仅仅显示存储的数据,因为它不是基于流的可观察变量。
至于显示产品列表,您执行相同的操作,但存储地图列表而不是单个地图。
如果您需要帮助,请分享您尝试添加和存储到PriceModel2
列表的方式。
推荐阅读
- python - 尝试将表单添加到 DetailView
- python-3.x - Groupby 列值并根据另一列值保留行
- kotlin - 通过 Kotlin 实现 PyTorch 和 DJL 之间的推理差异
- c# - MVVM DataGrid ComboBox SelectedValue 绑定
- sql - 来自 IFS 的 System i SQL 流文件
- php - 我无法使我的 .htaccess 文件与 MAMP 一起使用
- google-apps-script - 使用 Apps 脚本向 Google 表单添加选项时保留图像
- json - 使用反序列化数据访问字典中的数据
- amazon-dynamodb - 如何在 DynamoDB 和 Cognito 之间关联用户数据
- python - porter-stemmer:python 中的词干提取不起作用