Flutter学习12 - SharedPreferences

1、shared_preferences 插件

  • 类似于 Android 中的 SharedPreferences,键值对的形式进行本地存储

1.1、引入插件

在 pubspec.yaml 中引入

dart 复制代码
dependencies:
  shared_preferences: ^2.1.0

在需要用到的文件中引入

dart 复制代码
import 'package:shared_preferences/shared_preferences.dart';

1.2、基本用法

  • 写入数据
dart 复制代码
var sp = await SharedPreferences.getInstance();
sp.setString('name', 'Leon');
  • 读取数据
dart 复制代码
var sp = await SharedPreferences.getInstance();
var name = sp.getString('name');
  • 删除数据
dart 复制代码
var sp = await SharedPreferences.getInstance();
sp.remove('name');

2、代码示例

  • 工具类
dart 复制代码
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesUtils {
  static saveData<V>(String key, V value) async {
    var sp = await SharedPreferences.getInstance();
    var type = value.runtimeType;
    if (type == int) {
      sp.setInt(key, value as int);
    } else if (type == double) {
      sp.setDouble(key, value as double);
    } else if (type == String) {
      sp.setString(key, value as String);
    } else if (type == bool) {
      sp.setBool(key, value as bool);
    } else {
      print('类型不匹配');
    }
  }

  static getData(String key) async {
    var sp = await SharedPreferences.getInstance();
    print("sp.get:${sp.get(key)}");
    return sp.get(key);
  }

  static deleteAllData() async {
    var sp = await SharedPreferences.getInstance();
    for (String key in sp.getKeys()) {
      sp.remove(key);
    }
  }
}
  • 页面代码
dart 复制代码
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

const String KEY_NAME = "name";
const String KEY_AGE = "age";
const String KEY_WEIGHT = "weight";
const String KEY_BOOL = "bool";

class SpDemo extends StatefulWidget {
  const SpDemo({super.key});

  @override
  State<SpDemo> createState() => _SpDemoState();
}

class _SpDemoState extends State<SpDemo> {
  var _resultShow = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SpDemo'),
      ),
      body: Column(
        children: [
          ElevatedButton(onPressed: _saveData2Sp, child: const Text('保存数据')),
          ElevatedButton(onPressed: _getDataFromSp, child: const Text('获取数据')),
          ElevatedButton(onPressed: _deleteDataInSp, child: const Text('删除数据')),
          Text(_resultShow),
        ],
      ),
    );
  }

  void _saveData2Sp() async {
    await SharedPreferencesUtils.saveData(KEY_NAME, 'Leon');
    await SharedPreferencesUtils.saveData(KEY_AGE, 26);
    await SharedPreferencesUtils.saveData(KEY_WEIGHT, 60.5);
    await SharedPreferencesUtils.saveData(KEY_BOOL, true);
    setState(() {
      _resultShow = "保存成功";
    });
  }

  void _getDataFromSp() async {
    var name = await SharedPreferencesUtils.getData(KEY_NAME);
    var age = await SharedPreferencesUtils.getData(KEY_AGE);
    var weight = await SharedPreferencesUtils.getData(KEY_WEIGHT);
    var b = await SharedPreferencesUtils.getData(KEY_BOOL);
    print('姓名:$name\n年龄:$age\n体重:$weight\n其他:$b');
    setState(() {
      _resultShow = "姓名:$name\n年龄:$age\n体重:$weight\n其他:$b";
    });
  }

  void _deleteDataInSp() async {
    await SharedPreferencesUtils.deleteAllData();
    setState(() {
      _resultShow = "删除成功";
    });
  }
}
dart 复制代码
import 'package:flutter/material.dart';

import 'SharedPreferencesDemo.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Leon Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SpDemo(),
    );
  }
}
相关推荐
QQ同步助手33 分钟前
如何正确使用人工智能:开启智慧学习与创新之旅
人工智能·学习·百度
流浪的小新40 分钟前
【AI】人工智能、LLM学习资源汇总
人工智能·学习
A懿轩A2 小时前
C/C++ 数据结构与算法【数组】 数组详细解析【日常学习,考研必备】带图+详细代码
c语言·数据结构·c++·学习·考研·算法·数组
迷雾漫步者7 小时前
Flutter组件————FloatingActionButton
前端·flutter·dart
南宫生9 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
sanguine__10 小时前
Web APIs学习 (操作DOM BOM)
学习
数据的世界0112 小时前
.NET开发人员学习书籍推荐
学习·.net
coder_pig12 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
四口鲸鱼爱吃盐12 小时前
CVPR2024 | 通过集成渐近正态分布学习实现强可迁移对抗攻击
学习
捡芝麻丢西瓜14 小时前
flutter自学笔记5- dart 编码规范
flutter·dart