简体   繁体   English

如何在 Flutter 的 Shared Preferences 中获取和设置两种不同数据类型的值?

[英]How to get and set values of two different datatypes in Shared Preferences in Flutter?

I have a map named cardDetails whose details are fetched from firestore.我有一个名为cardDetails的 map,其详细信息是从 Firestore 中获取的。 Once the data is fetched, I want to used shared_preferences to save the details locally by converting the map to string and set the key to be true.获取数据后,我想使用shared_preferences通过将 map 转换为字符串并将密钥设置为 true 来在本地保存详细信息。 When the user opens the app again then, I check if the value has been read by using getBool(key) and then fetch the data from the string using getString(key) .当用户再次打开应用程序时,我检查是否已使用getBool(key)读取该值,然后使用getString(key)从字符串中获取数据。

The problem is that getString(key) is returning bool value instead of a string owing to which I cannot decode the string to map again问题是 getString(key) 返回 bool 值而不是字符串,因此我无法再次将字符串解码为 map

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building:
type 'bool' is not a subtype of type 'String'

Declaration and initialisation声明和初始化

Map<String, dynamic> cardDetails;
  var keys;
  bool _initialSharedValue;

  @override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((SharedPreferences sp) {
      sharedPreferences = sp;
      _initialSharedValue = sharedPreferences.getBool("homepage");
      // will be null if never previously saved
      if (_initialSharedValue == null) {
        _initialSharedValue = false;
        persist(_initialSharedValue); // set an initial value
      }
      setState(() {});
    });
  }

  Future<void> persist(bool value) async {
    setState(() {
      _initialSharedValue = value;
    });
    await sharedPreferences?.setBool("homepage", value);
  }

  storeCardInSharedPreference(Map cardDetails) async {
    await sharedPreferences?.setString("homepage", json.encode(cardDetails));
  }

In UI for building cards在用于构建卡片的 UI 中

    if (sharedPreferences.getBool("homepage"))
      ListView.builder(
        itemBuilder: (context, index) {
          cardDetails = json.decode(sharedPreferences.getString("homepage"));
          return HomepageCards(
            user: widget.user,
            cardDetails: cardDetails[cardDetails.keys.toList()[index]],
          );
        },
        itemCount: 3,
        scrollDirection: Axis.vertical,
        controller: _controller,
        shrinkWrap: true,
      )
    else
      StreamBuilder<DocumentSnapshot>(
        stream: Firestore()
            .collection('homepage')
            .document(widget.user.uid)
            .collection('h')
            .document('28032020')
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.data != null) {
            cardDetails = {};
            snapshot.data.data.forEach((index, individualDetail) {
              cardDetails[index] = individualDetail;
            });
            storeCardInSharedPreference(cardDetails);
            sharedPreferences.setBool("homepage", true);
            keys = snapshot.data.data.keys;
          } else {
            // TODO: Convert it to Shimmer with card skeletal layout
            CircularProgressIndicator();
          }

          return ListView.builder(
            itemBuilder: (context, index) {
              return HomepageCards(
                user: widget.user,
                cardDetails:
                    cardDetails[cardDetails.keys.toList()[index]],
              );
            },
            itemCount: keys.length,
            scrollDirection: Axis.vertical,
            controller: _controller,
            shrinkWrap: true,
          );
        },
      )

I solved the issue by using ?我通过使用解决了这个问题? in the if condition to make it a null-aware method invocation.在 if 条件中使其成为可识别 null 的方法调用。

if (sharedPreferences?.getBool("homepage"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter 如何在共享首选项中存储具有相同变量的值列表,然后从那里获取特定值 - Flutter How to store a list of values with same variable in shared preferences and then get the specific value from there 如何在 flutter 中一次检查共享首选项中是否存在多个值 - How to check if multiple values exist in shared preferences at once in flutter 如何在 Flutter 中的共享首选项中设置过期时间 - How to set expired time inside shared preferences in Flutter 如何在 flutter 中一次从共享首选项中检索多个值 - How to retrieve multiple values from shared preferences at once in flutter 如何在颤振中使用共享首选项? - how to use shared preferences in flutter? flutter 如何使用共享首选项保存和获取列表 - flutter how to save and get a list using shared preferences 如何使用 dart/flutter 中的共享首选项保存和获取列表列表 - How to save and get a list of lists using Shared preferences in dart/flutter 如何从 flutter 中的共享首选项中获取所有内容 - How to get all content from Shared Preferences in flutter 如何从 Flutter 中的共享首选项中获取和使用保存的语言/区域设置? - How to get and use saved language/locale from shared preferences in Flutter? Flutter Shared Preferences保存值,不显示 - Flutter Shared Preferences saving values, not displaying
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM