Image
LOADING
Innovative IT Solutions for Businesses of All Sizes

ARTICLE

Image
December 20 2022

Shared Preferences in Flutter

Image
Tea Cup
Go To Original Article
Photo by Fahim Muntashir on Unsplash

Shared preferences are a useful tool for storing small pieces of data in Flutter apps. They allow you to persist data across app launches and access it quickly and easily.

To use shared preferences in Flutter, you need to import the shared_preferences package and instantiate the SharedPreferences class. The SharedPreferences class provides several methods for storing and retrieving data, including setBool, setInt, setString, and getBool, getInt, getString.

Here’s an example of how to use shared preferences in Flutter:

import 'package:shared_preferences/shared_preferences.dart';

void main() async {
// get an instance of SharedPreferences
final prefs = await SharedPreferences.getInstance();

// set a boolean value
prefs.setBool('isLoggedIn', true);

// set an integer value
prefs.setInt('count', 42);

// set a string value
prefs.setString('username', 'john_doe');

// retrieve a boolean value
bool isLoggedIn = prefs.getBool('isLoggedIn');

// retrieve an integer value
int count = prefs.getInt('count');

// retrieve a string value
String username = prefs.getString('username');
}

In addition to the basic data types, shared preferences also support storing lists and sets using the setStringList and setStringSet methods. You can also use the remove method to delete a value from shared preferences.

It’s important to note that shared preferences are not suitable for storing large amounts of data or sensitive information. For more complex data storage needs, you should consider using a database or file storage.

In summary, shared preferences are a convenient way to store small pieces of data in Flutter apps. They are easy to use and allow you to persist data across app launches. However, they should not be used for storing large amounts of data or sensitive information.