📌  相关文章
📜  shared_preferences: 'latest version' (1)

📅  最后修改于: 2023-12-03 15:34:57.654000             🧑  作者: Mango

Introduction to shared_preferences

Shared preferences is a package for persisting key-value data on disk. It is widely used in Flutter applications for storing user preferences, settings, and other application data. The package provides a simple API for reading and writing data to the platform-specific storage location.

Installation

The shared_preferences package can be installed by adding it to the pubspec.yaml file of your Flutter project. The latest version can be specified as follows:

dependencies:
  shared_preferences: 'latest version'
Usage

To use shared preferences, import the package and access the shared preferences instance using the SharedPreferences.getInstance() method. This returns a Future that resolves to the shared preferences instance.

import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  // read and write data to shared preferences
}

Once you have the shared preferences instance, you can use it to write data to disk using the setX() methods, where X can be Bool, Double, Int, String, or StringList. You can then read the data back using the corresponding getX() methods.

await prefs.setBool('boolValue', true);
bool boolValue = prefs.getBool('boolValue') ?? false;

await prefs.setDouble('doubleValue', 3.14159);
double doubleValue = prefs.getDouble('doubleValue') ?? 0.0;

await prefs.setInt('intValue', 42);
int intValue = prefs.getInt('intValue') ?? 0;

await prefs.setString('stringValue', 'Hello, world!');
String stringValue = prefs.getString('stringValue') ?? '';

await prefs.setStringList('stringListValue', ['foo', 'bar']);
List<String> stringListValue = prefs.getStringList('stringListValue') ?? [];
Conclusion

Shared preferences provides a simple and efficient way to store and retrieve persistent data in Flutter applications. By using this package, you can easily save and retrieve user preferences, settings, and other application data on disk.