iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
Mobile Development

一起學Flutter,和我變Better!系列 第 28

Day 28 shared_preferences本機存放區

(一)介紹
Flutter推薦使用者使用shared_prederences儲存資料,可以存取少量資料到手機的xml文件中,大量資料則採用SQLite行動裝置資料庫或放在雲端。

(二)特性
1.為一個非同步、簡單、持久化且以key_value形式儲存的系統。
2.在Android端以SharedPreferences開發為基礎。
3.在iOS端以NSUserDefaults開發為基礎。

(三)在pubspec.yaml增加依賴
可以到https://pub.dev/packages/shared_preferences參考所需 版本。
https://ithelp.ithome.com.tw/upload/images/20211010/2014052477qPv1oD8N.png

(四)操作
•儲存資料
SharedPreferences prefs = await SharedPreferences.getInstance();
+
prefs.setString(key,value); //字串
prefs.setBool(key,value); //布林
prefs.setDouble(key,value); //浮點數
prefs.setInt(key,value); //整數
prefs.setStringList(key,value); //字串列表
•讀取資料
SharedPreferences prefs = await SharedPreferences.getInstance();
+
prefs.getString(key); //字串
prefs.getBool (key); //布林
prefs.getDouble (key); //浮點數
prefs.getInt (key); //整數
prefs.getStringList (key); //字串列表
•刪除資料
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key);

(五)實作
程式碼
https://ithelp.ithome.com.tw/upload/images/20211010/20140524S9QZGDesJ9.png
https://ithelp.ithome.com.tw/upload/images/20211010/20140524bxHxeV3xRA.png
https://ithelp.ithome.com.tw/upload/images/20211010/20140524fQbNNl2s58.png
執行畫面
https://ithelp.ithome.com.tw/upload/images/20211010/20140524dAdoKM6BJR.png

今天先介紹到這邊,明天將會介紹SQLite資料庫,敬請期待。

參考資料
橫跨Android及Apple的神話:用Dart語言神啟Flutter大業8.1節
http://tw-hkt.blogspot.com/2019/08/flutter-sharedpreferences.html
https://ithelp.ithome.com.tw/articles/10227342
https://pub.dev/packages/shared_preferences


上一篇
Day 27 自訂路由
下一篇
Day 29 SQLite資料庫
系列文
一起學Flutter,和我變Better!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言