Sign in
Topics

Launch Flutter apps faster with Rocket.new
Flutter SharedPreferences allows you to save and retrieve small data such as login states, counters, and theme choices without the need for a database. This blog explains setup, usage, examples, and best practices to optimize your Flutter projects with reliable storage.
Ever wondered how apps remember your login state or theme choice even after you close them? In Flutter, that smooth experience often comes from SharedPreferences.
Instead of setting up a full database for simple data like a string value, a boolean value, or an int value, you can persist key-value pairs quickly with Flutter SharedPreferences. It’s lightweight, reliable, and ideal for user preferences and small value storage across app sessions.
Shared preferences in Flutter provide a simple data storage option for persisting information that doesn’t require a full database. Developers often use it to store user preferences, login states, or app settings. The SharedPreferences class manages persistent storage through key-value pair mappings, helping you save data like string values, boolean values, int values, or double values efficiently.
Shared preference data is best suited for handling lightweight tasks such as keeping initial values, counter value updates, or saving boolean flags. Unlike complex relational data models, shared preferences only store key-value data.
SharedPreferences is a lightweight key–value storage solution in Flutter that allows developers to store small amounts of data locally on the device. It’s perfect for saving user preferences, settings, login states, or simple app data without the need for a full-fledged database. — Check out the full post here
Shared preferences are used when you want to persist data across sessions without the complexity of a database. For example, you can save data such as a string key containing a user’s theme choice, an integer value for login attempts, or a boolean value that toggles dark mode.
On Android, shared preference data is stored as an XML file, while on iOS, it resides in NSUserDefaults. Both platforms provide persistent storage automatically, so the developer only needs to focus on how to write data and read data through the SharedPreferences API.
Before using SharedPreferences in Flutter, you need to add it as a dependency in your Dart project. Open your YAML file and add the following line:
1dependencies: 2 shared_preferences: ^2.0.0 3
Run the following command to update your Flutter SDK dependencies:
1flutter pub get 2
After this step, you can use SharedPreferences in your Flutter projects by initializing an instance.
The sharedpreferences instance is obtained asynchronously. You need to call SharedPreferences prefs = await SharedPreferences.getInstance();. In practice, many developers shorthand this as prefs await sharedpreferences.getinstance.
1void main() async { 2 WidgetsFlutterBinding.ensureInitialized(); 3 SharedPreferences prefs = await SharedPreferences.getInstance(); 4 runApp(MyApp(prefs: prefs)); 5} 6
This setup ensures that your Flutter app can read data and write data from the very beginning when a user launches it.
Shared preferences can handle multiple data types, including string value, integer value, double value, and boolean value. Let’s explore how to write and read data using the setter and getter methods provided by the API.
Developers often need to store key-value data like usernames or tokens.
1prefs.setString('username', 'Vishal'); 2String? name = prefs.getString('username'); 3
This approach uses a string key and safely returns a null value if the data doesn’t exist.
Saving int values can help track user score, login count, or counter value.
1prefs.setInt('loginCount', 5); 2int? loginCount = prefs.getInt('loginCount'); 3
The API reads an integer value directly or returns a null value if the key doesn’t exist.
When working with small value calculations, such as ratings or pricing, you can save a double value.
1prefs.setDouble('rating', 4.5); 2double? rating = prefs.getDouble('rating'); 3
Saving double values is simple and avoids the overhead of handling databases for lightweight cases.
Boolean value storage is common for user preferences like dark mode toggles.
1prefs.setBool('darkMode', true); 2bool? isDark = prefs.getBool('darkMode'); 3
Saving boolean flags helps maintain a consistent user experience across multiple app launches.
Take your Flutter projects further with Rocket.new’s instant app generation. Go from idea to production-ready code with a single prompt.
Sometimes you need to remove data when a user logs out or resets their settings. SharedPreferences provides both remove data and delete data options.
1prefs.remove('username'); 2prefs.clear(); // Deletes all stored keys 3
The remove method helps target a given key, while clear removes all shared preference data at once.
When retrieving data from SharedPreferences, a null value might be returned if the key is missing. You should handle these cases gracefully by setting initial values. For example, while reading data for a counter, always provide a fallback.
1int counter = prefs.getInt('counter') ?? 0; 2
This guarantees predictable results during user launches.
Below is a practical Flutter app showing how to integrate SharedPreferences in Flutter.
1class MyApp extends StatelessWidget { 2 final SharedPreferences prefs; 3 const MyApp({Key? key, required this.prefs}) : super(key: key); 4 5 6 Widget build(BuildContext context) { 7 return MaterialApp( 8 home: MyHomePage(), 9 ); 10 } 11} 12 13class MyHomePage extends StatefulWidget { 14 15 _MyHomePageState createState() => _MyHomePageState(); 16} 17 18class _MyHomePageState extends State<MyHomePage> { 19 int counter = 0; 20 21 22 void initState() { 23 super.initState(); 24 _loadCounter(); 25 } 26 27 void _loadCounter() async { 28 SharedPreferences prefs = await SharedPreferences.getInstance(); 29 setState(() { 30 counter = prefs.getInt('counter') ?? 0; 31 }); 32 } 33 34 void _incrementCounter() async { 35 SharedPreferences prefs = await SharedPreferences.getInstance(); 36 setState(() { 37 counter++; 38 prefs.setInt('counter', counter); 39 }); 40 } 41 42 43 Widget build(BuildContext context) { 44 return Scaffold( 45 appBar: AppBar(title: Text("SharedPreferences Demo")), 46 body: Center(child: Text("Counter Value: $counter")), 47 floatingActionButton: FloatingActionButton( 48 onPressed: _incrementCounter, 49 child: Icon(Icons.add), 50 ), 51 ); 52 } 53} 54
This sample demonstrates class Myapp extends StatelessWidget, class Myhomepage extends StatefulWidget, and buildContext context usage along with build methods.
Shared preference is not designed for critical data or complex relational data. If you need structured storage or advanced queries, consider databases like Sqflite or Hive. SharedPreferences is best for small value settings, flags, or app preferences.
containsKey method to verify a given key exists before reading data.Modern app development often involves multiple platforms. While Flutter SDK is a strong choice, developers sometimes compare it with other tools. Below are the top 10 app development platforms offering enterprise-grade security and workflow support:
These platforms complement workflows where persistent storage, like a SharedPreferences instance, may be required for handling user preferences and local data.
Using SharedPreferences in Flutter makes it straightforward to persist key-value data across sessions. It supports storing string, double, integer, and boolean values with minimal overhead. Whether you want to read, write, or remove data, the API provides simple setter and getter methods.
While it should not be used for complex relational data, it is ideal for small value storage, user preferences, and lightweight app settings. By applying best practices, you can optimize your Flutter projects and make your apps more reliable for every user launch.