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(),
    );
  }
}
相关推荐
一只侯子1 小时前
Face AE Tuning
图像处理·笔记·学习·算法·计算机视觉
烤麻辣烫2 小时前
黑马程序员大事件后端概览(表现效果升级版)
java·开发语言·学习·spring·intellij-idea
烤麻辣烫3 小时前
黑马程序员苍穹外卖(新手)DAY6
java·开发语言·学习·spring·intellij-idea
Xudde.5 小时前
Quick2靶机渗透
笔记·学习·安全·web安全·php
fouryears_234176 小时前
现代 Android 后台应用读取剪贴板最佳实践
android·前端·flutter·dart
AA陈超6 小时前
Git常用命令大全及使用指南
笔记·git·学习
麦麦在写代码6 小时前
前端学习5
前端·学习
等你等了那么久7 小时前
Flutter国际化语言轻松搞定
flutter·dart
降临-max7 小时前
JavaSE---网络编程
java·开发语言·网络·笔记·学习
大白的编程日记.8 小时前
【计算网络学习笔记】MySql的多版本控制MVCC和Read View
网络·笔记·学习·mysql