【问题标题】:Flutter saving Map<String, Object> to Shared PreferencesFlutter 将 Map<String, Object> 保存到共享首选项
【发布时间】:2020-04-30 08:00:02
【问题描述】:

这是我存储 CartItems 的代码。

我想将它作为 cartItems 存储在 Shared Preferences 中,因为在刷新时,数据会丢失。 我还想在 CartItem 中有功能来检查产品是否在购物车中,以便我可以选中/取消选中它。

class CartItem {
  final String id;
  final String prodID;
  final String title;
  final String img;
  final double quantity;
  final double price;
  final double availQuantity;

  CartItem({
    @required this.id,
    @required this.prodID,
    @required this.title,
    @required this.quantity,
    @required this.price,
    @required this.img,
    this.availQuantity,
  });

}

class Cart with ChangeNotifier {
  Map<String, CartItem> _items = {};
  Map<String, CartItem> get items {
    return {..._items};
  }

  int get itemCount {
    return _items.length;
  }
  void addItem(String productId, double price, String title, String img,
      double availQuantity) {
    if (_items.containsKey(productId)) {
      _items.update(
        productId,
        (existingCartItem) => CartItem(
          id: existingCartItem.id,
          title: existingCartItem.title,
          img: existingCartItem.img,
          price: existingCartItem.price,
          quantity: existingCartItem.quantity + 1,
          availQuantity: existingCartItem.availQuantity,
        ),
      );
    } else {
      _items.putIfAbsent(
        productId,
        () => CartItem(
          id: productId,
          title: title,
          img: img,
          price: price,
          quantity: 1,
          availQuantity: availQuantity,
        ),
      );
    }

    notifyListeners();
  }

}

我尝试了很多方法来转换为字符串并调用 setString(), 也转换为列表。但无法完成。 需要帮助。

【问题讨论】:

  • 购物车应该保留在服务器右侧
  • 我推荐你用 sqflite 来做flutter
  • 我不想保存到服务器。

标签: flutter sharedpreferences shopping-cart


【解决方案1】:

可以看到保存在 sharedPreference 中的函数, 你有没有尝试将旅游Cart转换成Map&lt;String, dynamic&gt;并保存。我认为您尝试直接保存您的 Cart 类,但这是不允许的,您只能保存 intstringListMap ...

【讨论】:

  • 如何将其转换为 Map 并保存。
  • 你可以为此创建一个函数或一个getter
  • Map&lt;String, dynamic&gt; toMap() { return { "id": this.id "prodID": this.prodID "title": this.title "img": this.img "quantity": this.quantity "price": this.price "availQuantity": this.availQuantity } }
【解决方案2】:

如果将 Map 转换为 String 则可以存储它,如下所示:

import 'dart:convert';
...
String mapToStr = json.encode(map);

当您想从共享首选项中取出字符串并再次将其用作 Map 时,请再次将其从 String 解码为 Map,如下所示:

Map<String, Object> strToMap = json.decode(mapToStr);

【讨论】:

    【解决方案3】:

    您可以通过此代码检查产品是否在购物车中:

    bool checkProductAddedToCart(productId) {
       if (_items.containsKey(productId)) {
          return true;
       } else {
          return false;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2014-01-11
      • 2021-10-02
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2022-01-15
      相关资源
      最近更新 更多