Flutter 本地存储shared_preferences

shared_preferences是一个简单的,异步的,持久化的key-value存储系统。

地址:https://pub.dev/packages/shared_preferences

写入数据

// Obtain shared preferences.
final 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']);

读取数据

// 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 data for the 'counter' key.
final success = await prefs.remove('counter');

封装shared_preferences

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class Storage{
  static setData(String key,dynamic value) async{
    SharedPreferences pref=await SharedPreferences.getInstance();
    pref.setString(key, json.encode(value));
  }
  static getData(String key) async{
    SharedPreferences pref=await SharedPreferences.getInstance();
    String? data=pref.getString(key);
    return json.decode(data!);
  }
  static removeData(String key) async{
    SharedPreferences pref=await SharedPreferences.getInstance();
    return pref.remove(key);
  }
}

results matching ""

    No results matching ""