💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] > [home](https://pub.dev/packages/shared_preferences) ## 概述 为简单数据(iOS 和 macOS 上的 NSUserDefaults,Android 上的 SharedPreferences 等)包装特定于平台的持久性存储。数据可能会异步持久化到磁盘,并且无法保证返回后写入将持久化到磁盘上,因此此插件不得用于存储关键数据。 支持列表 |Android | iOS | Linux | macOS | Web | Windows | | --- | --- | --- | --- | --- | --- | | **Support** | SDK 16+ | 12.0+ | Any | 10.14+ | Any | Any | 存储方案 | Platform | Location | | :-- | :-- | | Android | SharedPreferences | | iOS | NSUserDefaults | | Linux | In the XDG\_DATA\_HOME directory | | macOS | NSUserDefaults | | Web | LocalStorage | | Windows | In the roaming AppData directory | ## 示例 ### Write data ``` // Obtain shared preferences. final SharedPreferences prefs = await SharedPreferences.getInstance(); // Save an integer value to 'counter' key. await prefs.setInt('counter', 10); // Save an boolean value to 'repeat' key. await prefs.setBool('repeat', true); // Save an double value to 'decimal' key. await prefs.setDouble('decimal', 1.5); // Save an String value to 'action' key. await prefs.setString('action', 'Start'); // Save an list of strings to 'items' key. await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']); ``` ### Read data ``` // Try reading data from the 'counter' key. If it doesn't exist, returns null. final int? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. final bool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. final double? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. final String? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. final List<String>? items = prefs.getStringList('items'); ``` ## remove ``` // Remove data for the 'counter' key. await prefs.remove('counter'); ``` ## 示例 在 flutter 中使用 ``` _get() async { //mock await Future.delayed(const Duration(seconds: 2)); final SharedPreferences prefs = await SharedPreferences.getInstance(); var string1 = prefs.getString("key"); setState(() { if(string1 != null){ _title=string1; }else{ _title="asdad"; } }); } _set() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString("key", "helo"); } ```