Last updated:
0 purchases
sharedpreference
sharedpreference #
A new Flutter package for sharedpreference.
Getting Started #
读取和存储本地sp文件.
github项目主页地址
安装依赖 #
dependencies:
sharedpreference: xx
copied to clipboard
使用方法 #
在已安装依赖的前提下,按如下操作完成:
应用初始化
try{
var result =await SharedPreference.instance.init();
print('result is $result');
}catch(e){
print('error is $e');
}
正常输出:
I/flutter (23132): init is 初始化成功.
如有异常请自行排查.
copied to clipboard
新建序列化对象
part 'user.g.dart';
@JsonSerializable()
class User{
String name;
int age;
User(this.name,this.age);
String get names=>this.name;
set names(String _names)=>this.name=_names;
factory User.fromJson(Map<String,dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
copied to clipboard
设置值
//String
SharedPreference.instance.set('data1', 'abc');
//int
SharedPreference.instance.set('data2', 123);
//bool
SharedPreference.instance.set('data3', false);
//double
SharedPreference.instance.set('data4', 123.0);
//List<String>
SharedPreference.instance.set('data5', ['a','b','c']);
//User 设置序列化对象(对象一定要是序列化的哦)
SharedPreference.instance.set('data6', User('jack',100));
//List<User>
SharedPreference.instance.set('data7',[User('xiaoming',100),User('hua',100),User('qiang',100)] );
copied to clipboard
获取值
SharedPreference.instance.get('data1')
如果要获取序列化的对象则采用如下方式:
var user=SharedPreference.instance.get('data6',serializable: true);
print('user.name is ${user['name']}');
var users=SharedPreference.instance.get('data7',serializable: true);
print('users[0].name is ${users[0]['name']}');
输出:
I/flutter (23132): data1 is abc
I/flutter (23134): users[0].name is xiaoming
copied to clipboard
删除key
SharedPreference.instance.removeKey('key');
copied to clipboard
清空
SharedPreference.instance.clear();
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.