如何解决Flutter 从 GetStorage List 中获取数据值
我想从 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 中初始化您的控制器和存储。
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
列表的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。