Flutter shared_preferences本地存储

Posted 伟雪无痕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter shared_preferences本地存储相关的知识,希望对你有一定的参考价值。

一.shared_preferences简单介绍

1.在android中,您可以使用SharedPreferences API存储一些键值对,在Flutter中,您可以通过使用插件Shared_Preferences来访问此功能,这个插件包装了Shared Preferences和NSUserDefaults(与ios相同)的功能。

2.SharedPreferences引用

1).pubspec.yaml中添加依赖,eg:

shared_preferences: ^2.0.11

2).dart文件中导入包

import 'package:shared_preferences/shared_preferences.dart';

3.SharedPreferences源码查看

1).设置键值类型

/// Saves a boolean [value] to persistent storage in the background.
  Future<bool> setBool(String key, bool value) => _setValue('Bool', key, value); //设置boolean型值存储

  /// Saves an integer [value] to persistent storage in the background.
  Future<bool> setInt(String key, int value) => _setValue('Int', key, value); //设置int型值存储

  /// Saves a double [value] to persistent storage in the background.
  ///
  /// Android doesn't support storing doubles, so it will be stored as a float.
  Future<bool> setDouble(String key, double value) =>
      _setValue('Double', key, value); //设置double型值存储

  /// Saves a string [value] to persistent storage in the background.
  ///
  /// Note: Due to limitations in Android's SharedPreferences,
  /// values cannot start with any one of the following:
  ///
  /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu'
  /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy'
  /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu'
  Future<bool> setString(String key, String value) =>
      _setValue('String', key, value); //设置string型值存储

  /// Saves a list of strings [value] to persistent storage in the background.
  Future<bool> setStringList(String key, List<String> value) =>
      _setValue('StringList', key, value); 设置list存储

2).获取键值类型

/// Returns all keys in the persistent storage.
  Set<String> getKeys() => Set<String>.from(_preferenceCache.keys); //获取preference中所有的keys

  /// Reads a value of any type from persistent storage.
  Object? get(String key) => _preferenceCache[key];

  /// Reads a value from persistent storage, throwing an exception if it's not a
  /// bool.
  bool? getBool(String key) => _preferenceCache[key] as bool?;

  /// Reads a value from persistent storage, throwing an exception if it's not
  /// an int.
  int? getInt(String key) => _preferenceCache[key] as int?;

  /// Reads a value from persistent storage, throwing an exception if it's not a
  /// double.
  double? getDouble(String key) => _preferenceCache[key] as double?;

  /// Reads a value from persistent storage, throwing an exception if it's not a
  /// String.
  String? getString(String key) => _preferenceCache[key] as String?;

  /// Returns true if persistent storage the contains the given [key].
  bool containsKey(String key) => _preferenceCache.containsKey(key); //判断是否包含某个键值

  /// Reads a set of string values from persistent storage, throwing an
  /// exception if it's not a string set.
  List<String>? getStringList(String key)  //获取键值列表
    List<dynamic>? list = _preferenceCache[key] as List<dynamic>?;
    if (list != null && list is! List<String>) 
      list = list.cast<String>().toList();
      _preferenceCache[key] = list;
    
    // Make a copy of the list so that later mutations won't propagate
    return list?.toList() as List<String>?;
  

二.sharedpreferencestest.dart demo展示,可通过logcat查看log中点击的次数,eg:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesTest extends StatefulWidget
  const SharedPreferencesTest(Key? key) : super(key: key);

  @override
  State<StatefulWidget> createState() => _SharedPreferencesState();



class  _SharedPreferencesState extends State<SharedPreferencesTest>
  var pressTime=0;
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: new Scaffold(
        body: new Center(
          child: new RaisedButton(
            onPressed: _incrementCounter,
            child: new Text('Click me!'),
          ),
        ),
      ),
    );
  

  _incrementCounter() async 
    setState(() async 
      SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
      int counterNum= (sharedPreferences.getInt('countnum') ?? 0) + 1;
      sharedPreferences.setInt('countnum', counterNum);
      print('Click the count num is $counterNum');
    );
  

以上是关于Flutter shared_preferences本地存储的主要内容,如果未能解决你的问题,请参考以下文章

Flutter shared_preferences本地存储

Flutter:删除所有已保存的shared_preferences首选项

Flutter Web 的 Shared_Preferences?

flutter中本地存储shared_preferences的使用

Flutter 测试:MissingPluginException(在通道 plugins.flutter.io/shared_preferences 上找不到方法 getAll 的实现)

Flutter 持久化_shared_preferences