DEV Community

Cover image for How to store Data with shared Preference in Flutter
Irene Duke
Irene Duke

Posted on

1 1

How to store Data with shared Preference in Flutter

In Flutter, you can use the shared_preferences package to store and retrieve data using shared preferences easily. Shared preferences are a simple way to store key-value pairs persistently across user sessions.

  1. Add the shared_preferences dependency to your pubspec.yaml file:-

dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.0

  1. Import the shared_preferences package in your Dart file:-

import 'package:shared_preferences/shared_preferences.dart';

3.Storing Data with Shared Preferences:

Future saveData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

// Storing data
prefs.setString('username', 'JohnDoe');
prefs.setInt('age', 30);
prefs.setBool('isLogged', true);

print('Data saved to shared preferences.');
}

4.Retrieving Data from Shared Preferences:

Future loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

// Retrieving data
String? username = prefs.getString('username');
int? age = prefs.getInt('age');
bool? isLogged = prefs.getBool('isLogged');

print('Username: $username');
print('Age: $age');
print('Logged in: $isLogged');
}

5.Clearing Data from Shared Preferences:

Future clearData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

// Clearing specific data
prefs.remove('username');

// Clearing all data
// prefs.clear();

print('Data cleared from shared preferences.');
}

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay