[Flutter]使用SharedPreferences記錄使用者設定/資料

安裝

pub.dev

使用Flutter

flutter pub add shared_preferences

添加到pubspec.yaml中

dependencies:
  shared_preferences: ^2.0.5

引入

import 'package:shared_preferences/shared_preferences.dart';

使用方法

實體化

SharedPreferences prefs = await SharedPreferences.getInstance();

寫入資料

//string
await prefs.setString(key, value);

//boolean
await prefs.setBool(key, value);

//float
await prefs.setDouble(key, value);

//integer
await prefs.setInt(key, value);

//stringlist
await prefs.setStringList(key, value);

讀取資料

//string
prefs. getString(key);

//boolean
prefs.getBool(key);

//float
prefs.getDouble(key);

//integer
prefs.getInt(key);

//stringlist
prefs.getStringList(key);

刪除指定資料

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key);

移除所有資料

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();

例子

class _HomePageState extends State<HomePage> {
  final String prefData = "prefData";
  String _data = '';
  
  //初始化
  @override
    void initState() {
    super.initState();
    _load();
  }

  //獲取資料
  _load() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      setState(() {
        _data = (prefs.getString(prefData) ?? 0);
      });
    }

  //寫入資料
  _save(String name) async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      setState(() {
        _data = name;
        prefs.setInt(prefData, _data);
      });
    }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SharedPreferences demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'SharedPreferences demo',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _save('Sandy'),
        child: Icon(Icons.data_usage),
      ),
    );
  }
}
0 0 評分數
Article Rating
訂閱
通知
guest

0 Comments
在線反饋
查看所有評論