To delete a key from SharedPreferences in Flutter, you can use the remove()
method. Firstly, import the necessary package:
<script>
import 'package:shared_preferences/shared_preferences.dart';
</script>
Then, you can remove a specific key by calling the remove()
method as shown below:
<script>
void deleteKey() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.remove('your_key');
}
</script>
In the code snippet above, we first obtain an instance of SharedPreferences by calling getInstance()
method. After that, we use the obtained preferences object to delete a specific key by calling remove()
method and passing the key as a parameter (replace 'your_key'
with the actual name of the key you want to delete).
Here’s an example of how you can use the deleteKey()
function in a Flutter application:
<script>
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
void deleteKey() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.remove('your_key');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Delete Key Example'),
),
body: Center(
child: RaisedButton(
onPressed: deleteKey,
child: Text('Delete Key'),
),
),
),
);
}
}
</script>
The code above sets up a simple Flutter application with a button. When the button is pressed, it calls the deleteKey()
function which deletes the specified key from the SharedPreferences. You can replace 'your_key'
with the actual key you want to delete.