// 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']);
读取数据:
1 2 3 4 5 6 7 8 9 10
// Try reading data from the 'counter' key. If it doesn't exist, returns null. finalint? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. finalbool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. finaldouble? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. finalString? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. finalList<String>? items = prefs.getStringList('items');
通过 Key 删除数据:
1 2
// Remove data for the 'counter' key. await prefs.remove('counter');