如何使用shared_preferences
pubspec.yaml文件中添加依賴
dependencies:
flutter:
sdk: flutter
shared_preferences:^0.5.1+
導入頭文件
import 'package:shared_preferences/shared_preferences.dart';
存儲數據
final prefs = await SharedPreferences.getInstance();
prefs.setInt('counter', counter);
讀取使用
final prefs = await SharedPreferences.getInstance();
final counter = prefs.getInt('counter') ?? 0;
移除數據
final prefs = await SharedPreferences.getInstance();
prefs.remove('counter');
shared_preferences有哪些常用的API
shared_preferences支持int,double,bool,string與stringList類型的數據存儲
對應API為setString,setBool等,讀取為getString,getBool,直接使用get獲取到的是dynamic類型
getKeys可以獲取到所有的key
基于shared_preferences實現計數器Demo
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("shared_preference"),),
body:_CounterWidget(),
),
));
}
class _CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<_CounterWidget> {
String countString = '';
String localCount = '';
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
RaisedButton(onPressed: _incrementCounter, child: Text("增加"),),
RaisedButton(onPressed: _getCounter, child: Text('獲取'),),
Text(
countString,
style: TextStyle(fontSize: 20),
),
Text(
'result' + localCount,
style: TextStyle(fontSize: 20),
)
],
),
);
}
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
countString = countString + "1";
});
int counter = (prefs.getInt('counter') ?? 0) + 1;
await prefs.setInt('counter', counter);
}
_getCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
localCount = prefs.getInt('counter').toString();
});
}
}
注:使用蘋果設備xcode中需要安裝cocoapods
brew install cocoapods