赞
踩
设置值:
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();
var data=prefs.getString("name");
删除值:
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
prefs.clear();//清空键值对
完整代码:
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class StoragePage extends StatefulWidget { StoragePage({Key key}) : super(key: key); _StoragePageState createState() => _StoragePageState(); } class _StoragePageState extends State<StoragePage> { _saveData() async{ SharedPreferences sp=await SharedPreferences.getInstance(); sp.setString("username", "张三111"); sp.setString("age", "26"); } _getData() async{ SharedPreferences sp=await SharedPreferences.getInstance(); print(sp.getString("username")); print(sp.getString("age")); } _removeData() async{ SharedPreferences sp=await SharedPreferences.getInstance(); print(sp.remove("age")); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("本地存储"), ), body: Center( child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ RaisedButton( child: Text('保存数据'), onPressed: _saveData, ), SizedBox(height: 10), RaisedButton( child: Text('获取数据'), onPressed:_getData, ), SizedBox(height: 10), RaisedButton( child: Text('清除数据'), onPressed:_removeData, ) ]), ), ); } }
简单封装:
import 'package:shared_preferences/shared_preferences.dart'; class Storage{ static Future<void> setString(key,value) async{ SharedPreferences sp=await SharedPreferences.getInstance(); sp.setString(key, value); } static Future<String> getString(key) async{ SharedPreferences sp=await SharedPreferences.getInstance(); return sp.getString(key); } static Future<void> remove(key) async{ SharedPreferences sp=await SharedPreferences.getInstance(); sp.remove(key); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。