我想从 GetStorage() 获取数据,
我有一个商店列表,我可以将其用作唯一页面的静态,这样我可以将我的列表保存在 GetStorage 中,如果我转到另一个也会显示的页面。就像共享首选项一样。我如何显示来自 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
的 map 可以阅读。
将此添加到您的 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 中初始化 Controller 和存储。
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
只是为了显示存储的数据,因为它不是基于可观察流的变量。
至于显示产品列表,您可以执行相同的操作,但存储 map 列表而不是单个 map 。
如果您需要这方面的帮助,请分享您如何尝试添加和存储到 PriceModel2
列表。
关于android - Flutter从GetStorage列表中获取数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68520975/