Flutter 缓存数据 shared_preferences插件配置

Flutter 缓存文本变量 shared_preferences插件配置

1.载入插件

 flutter pub add shared_preferences

2.初始化 在main.dart 入口文件配置

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); //初始化缓存
  
   runApp(const MyApp());
}

3.设置权限(必须)

未设置测报错:[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel., null, null)

【Android】

在AndroidManifest.xml文件中添加了这些权限:

路径1安卓配置:android/app/src/main/AndroidManifest.xml

路径2安卓配置:android/app/src/profile/AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

【IOS】

在ios/Podfile目录文件中添加了这些权限:

路径IOS配置:ios/Podfile

添加如下配置:(文件默认存在,但使用#注释掉了,去掉注释符即可)

platform :ios, '11.0' 

4.运行重载权限配置

终端运行:

 sudo pod install

5.重新运行项目

6.插件属性使用:

ElevatedButton(
            onPressed: () async {
              final prefs = await SharedPreferences.getInstance(); //异步引用
              await prefs.setString('name', 'John'); //存储文本
              print(prefs.getString('name')); //读取文本

              await prefs.setInt('name', 123); //存储整型
              print(prefs.getInt('name')); //读取

              await prefs.setBool('name', true); //存储布尔
              print(prefs.getBool('name')); //读取

              await prefs.setDouble('name', 3.14159); //存储小数
              print(prefs.getDouble('name')); //读取

              await prefs.setStringList('name', ['1', '2']); //存储文本数组
              print(prefs.getStringList('name')); //读取

              prefs.remove('name'); //删除指定键
              prefs.clear(); //清空整个缓存

            },
            child: Text("示例"),
          ),

434 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注