【從零開始學 Flutter 程式設計】SharedPreferences 設定檔資料存取

【從零開始學 Flutter 程式設計】線上教學課程目錄 使用 Dart 程式語言,開發 Android 和 iOS APP 應用程式。

SharedPreferences 設定檔資料存取

SharedPreferences 設定檔資料存取,類似 Android 的 Shared Preferences 和 iOS 的 NSUserDefaults,可以存取一些基本的少量資料存到手機端的xml文件中,大量資料則會改採用 SQLite 行動裝置資料庫或是存放在雲端,如: FireBase。

在 pubspec.yaml 文件中添加依賴

最新版號,可以連結至 pub.dev: shared_preferences:https://pub.dev/packages/shared_preferences
shared_preferences: "^0.5.3"

加入位置實際範例

載入Lib

要使用 SharedPreferences,宣告載入Lib
import 'package:shared_preferences/shared_preferences.dart';

實體化 SharedPreferences

別忘記要加入非同處理 await 關鍵字
SharedPreferences prefs = await SharedPreferences.getInstance();

設定寫入 SharedPreferences 資料

其中 key 是儲存的名字,value 是儲存的資料,別忘記要加入非同處理 await 關鍵字
//字串資料
await prefs.setString(key, value);

//布林資料
await prefs.setBool(key, value);

//浮點數資料
await prefs.setDouble(key, value);

//整數資料
await prefs.setInt(key, value);

//字串列表資料
await prefs.setStringList(key, value);

讀取 SharedPreferences 資料

其中 key 是儲存的名字。
//字串資料
prefs. getString(key);

//布林資料
prefs.getBool(key);

//浮點數資料
prefs.getDouble(key);

//整數資料
prefs.getInt(key);

//字串列表資料
prefs.getStringList(key);

删除指定 key資料

其中 key 是儲存的名字。
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键

移除所有 SharedPreferences 資料

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();//清空键值对

存取 SharedPreferences 整數範例

_saveDate() async {
  //實體化
  SharedPreferences prefs = await SharedPreferences.getInstance();
  
  //獲取 counter 為 null 則預設值設定為 0
  int counter = (prefs.getInt('counter') ?? 0);
  
  //寫入
  await prefs.setInt('counter', counter);
}

計數器

原本若沒有 SharedPreferences,APP整個關閉,下次再開啟計數器,則不會紀錄上一次的資料。

完整程式碼

沒有記憶的計數器,重開APP,計數歸零重來。
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: HomePage(title: 'HKT線上教室'),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme
                  .of(context)
                  .textTheme
                  .display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

執行畫面

改成會記憶的計數器

初始化資料

flutter 生命週期,最一開始 initState ,載入計數資料
@override
void initState() {
super.initState();
_loadCounter();
}

獲取計數資料

 _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt(prefCounter) ?? 0);
    });
  }

設定寫入計數資料

  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt(prefCounter) ?? 0) + 1;
      prefs.setInt(prefCounter, _counter);
    });
  }

完整程式碼

有記憶的計數器,重開APP,計數會是上次最後一次的結果
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: HomePage(title: 'HKT線上教室'),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final String prefCounter = "prefCounter";
  int _counter = 0;

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

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt(prefCounter) ?? 0);
    });
  }

  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt(prefCounter) ?? 0) + 1;
      prefs.setInt(prefCounter, _counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

執行畫面

參考資料

pub.dev: shared_preferences
https://pub.dev/packages/shared_preferences

那這次的課程就介紹到這邊囉~
順帶一提,KT 線上教室,臉書粉絲團,會不定期發佈相關資訊,不想錯過最新資訊,不要忘記來按讚,加追蹤喔!也歡迎大家將這套課程分享給更多人喔。
我們下次再見囉!!!掰掰~

這個網誌中的熱門文章

2023 最新入門零基礎 Kotlin教學【從零開始學 Kotlin 程式設計】Kotlin 教學課程目錄 (Android Kotlin, IntelliJ IDEA, Android Studio, Android APP 開發教學)

2022 最新入門零基礎 Flutter教學 【Flutter 程式設計入門實戰 30 天】Flutter 教學課程目錄 (IntelliJ IDEA 開發教學)

nano 文字編輯器

16天記下7000單字

startActivityForResult is deprecated 已廢棄替代解決方式