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



我有一张名为cardDetails的地图,其详细信息是从消防仓库获取的。获取数据后,我想使用shared_preferences通过将映射转换为字符串并将键设置为true来本地保存详细信息。当用户再次打开应用程序时,我会使用getBool(key)检查是否已读取该值,然后使用getString(key)从字符串中获取数据。

问题是getString(key(返回的是bool值而不是字符串,因此我无法解码字符串以再次映射

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

申报和初始化

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));
}

在建筑卡的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,
);
},
)

我通过在if条件中使用?使其成为一个null感知方法调用来解决这个问题。

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

相关内容

  • 没有找到相关文章

最新更新