![](/img/trans.png)
[英]Flutter How to store a list of values with same variable in shared preferences and then get the specific value from there
[英]How to get and set values of two different datatypes in Shared Preferences in Flutter?
我有一個名為cardDetails
的 map,其詳細信息是從 Firestore 中獲取的。 獲取數據后,我想使用shared_preferences
通過將 map 轉換為字符串並將密鑰設置為 true 來在本地保存詳細信息。 當用戶再次打開應用程序時,我檢查是否已使用getBool(key)
讀取該值,然后使用getString(key)
從字符串中獲取數據。
問題是 getString(key) 返回 bool 值而不是字符串,因此我無法再次將字符串解碼為 map
════════ 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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.