### Example pubspec.yaml Entry Source: https://pub.dev/packages/shared_preferences_macos/install This is an example of how the shared_preferences_macos dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: shared_preferences_macos: ^2.0.5 ``` -------------------------------- ### Add shared_preferences_ios to pubspec.yaml Source: https://pub.dev/packages/shared_preferences_ios/install This is an example of how the shared_preferences_ios dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: shared_preferences_ios: ^2.1.1 ``` -------------------------------- ### SharedPreferences Builder Example Source: https://pub.dev/packages/shared_preferences/example This snippet shows how to use SharedPreferences within a builder function, handling different connection states. ```dart builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.waiting || snapshot.connectionState == ConnectionState.none) { return const CircularProgressIndicator(); } return builder(context); }, ); ``` -------------------------------- ### SharedPreferences Demo App Source: https://pub.dev/packages/shared_preferences_macos/example This is the main example application demonstrating the usage of shared_preferences_macos. It includes functionality to increment a counter and display its value, which persists between app launches. ```dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({Key? key}) : super(key: key); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State { final SharedPreferencesStorePlatform _prefs = SharedPreferencesStorePlatform.instance; late Future _counter; // Includes the prefix because this is using the platform interface directly, // but the prefix (which the native code assumes is present) is added by the // app-facing package. static const String _prefKey = 'flutter.counter'; Future _incrementCounter() async { final Map values = await _prefs.getAll(); final int counter = ((values[_prefKey] as int?) ?? 0) + 1; setState(() { _counter = _prefs.setValue('Int', _prefKey, counter).then((bool success) { return counter; }); }); } @override void initState() { super.initState(); _counter = _prefs.getAll().then((Map values) { return (values[_prefKey] as int?) ?? 0; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SharedPreferences Demo'), ), body: Center( child: FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return const CircularProgressIndicator(); default: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } })), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Add shared_preferences_android to pubspec.yaml Source: https://pub.dev/packages/shared_preferences_android/install This is an example of how the shared_preferences_android dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: shared_preferences_android: ^2.4.25 ``` -------------------------------- ### Basic Flutter Web App Setup Source: https://pub.dev/packages/shared_preferences_web/example This is the main entry point for a Flutter web application using the shared_preferences_web package. It sets up a basic Material App structure and displays a testing message. Look at the console output for results. ```dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } /// App for testing class MyApp extends StatefulWidget { /// Default Constructor const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return const Directionality( textDirection: TextDirection.ltr, child: Text('Testing... Look at the console output for results!'), ); } } ``` -------------------------------- ### SharedPreferences Windows Example App Source: https://pub.dev/packages/shared_preferences_windows/example This is the main Dart file for a Flutter application demonstrating the use of shared_preferences_windows. It includes functionality to increment a counter and display its value, which persists between app sessions. ```dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:shared_preferences_windows/shared_preferences_windows.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({super.key}); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State { final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; final SharedPreferencesWindowsOptions options = const SharedPreferencesWindowsOptions(); static const String _counterKey = 'counter'; late Future _counter; Future _incrementCounter() async { final int? value = await _prefs!.getInt(_counterKey, options); final int counter = (value ?? 0) + 1; setState(() { _counter = _prefs.setInt(_counterKey, counter, options).then((_) { return counter; }); }); } Future _getAndSetCounter() async { setState(() { _counter = _prefs!.getInt(_counterKey, options).then((int? counter) { return counter ?? 0; }); }); } @override void initState() { super.initState(); _getAndSetCounter(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SharedPreferences Demo'), ), body: Center( child: FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const CircularProgressIndicator(); case ConnectionState.active: case ConnectionState.done: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } })), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Import shared_preferences_web in Dart Source: https://pub.dev/packages/shared_preferences_web/install Import the package into your Dart files to start using its functionalities. Ensure this line is present at the top of your Dart file. ```dart import 'package:shared_preferences_web/shared_preferences_web.dart'; ``` -------------------------------- ### SharedPreferencesWithCache Operations Source: https://pub.dev/packages/shared_preferences Illustrates using SharedPreferencesWithCache with an allow list for cache options. It covers setting, getting, removing, and clearing entries. ```dart final SharedPreferencesWithCache prefsWithCache = await SharedPreferencesWithCache.create( cacheOptions: const SharedPreferencesWithCacheOptions( // When an allowlist is included, any keys that aren't included cannot be used. allowList: {'repeat', 'action'}, ), ); await prefsWithCache.setBool('repeat', true); await prefsWithCache.setString('action', 'Start'); final bool? repeat = prefsWithCache.getBool('repeat'); final String? action = prefsWithCache.getString('action'); await prefsWithCache.remove('repeat'); // Since the filter options are set at creation, they aren't needed during clear. await prefsWithCache.clear(); ``` -------------------------------- ### Import shared_preferences_macos in Dart Source: https://pub.dev/packages/shared_preferences_macos/install Import the package into your Dart files to start using its functionalities. Ensure you have added the dependency first. ```dart import 'package:shared_preferences_macos/shared_preferences_macos.dart'; ``` -------------------------------- ### Import shared_preferences_windows in Dart Source: https://pub.dev/packages/shared_preferences_windows/install Import the package into your Dart code to start using its functionalities for Windows shared preferences. ```dart import 'package:shared_preferences_windows/shared_preferences_windows.dart'; ``` -------------------------------- ### Import shared_preferences_ios in Dart Code Source: https://pub.dev/packages/shared_preferences_ios/install Import the package into your Dart files to start using its functionalities. ```dart import 'package:shared_preferences_ios/shared_preferences_ios.dart'; ``` -------------------------------- ### SharedPreferences Linux Example App Source: https://pub.dev/packages/shared_preferences_linux/example This is the main Dart file for a Flutter application demonstrating the use of shared_preferences_linux. It includes functionality to increment a counter, retrieve its value, and display it, ensuring the value persists between sessions. ```Dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:shared_preferences_linux/shared_preferences_linux.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({super.key}); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State { final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; final SharedPreferencesLinuxOptions options = const SharedPreferencesLinuxOptions(); static const String _counterKey = 'counter'; late Future _counter; Future _incrementCounter() async { final int? value = await _prefs!.getInt(_counterKey, options); final int counter = (value ?? 0) + 1; setState(() { _counter = _prefs.setInt(_counterKey, counter, options).then((_) { return counter; }); }); } Future _getAndSetCounter() async { setState(() { _counter = _prefs!.getInt(_counterKey, options).then((int? counter) { return counter ?? 0; }); }); } @override void initState() { super.initState(); _getAndSetCounter(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SharedPreferences Demo'), ), body: Center( child: FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const CircularProgressIndicator(); case ConnectionState.active: case ConnectionState.done: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } })), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Configure Android SharedPreferences Backend Source: https://pub.dev/packages/shared_preferences_android Use SharedPreferencesAsyncAndroidOptions to specify the Android SharedPreferences backend. This example shows how to configure it to use the native Android SharedPreferences with a custom file name. ```dart const SharedPreferencesAsyncAndroidOptions options = SharedPreferencesAsyncAndroidOptions( backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( fileName: 'the_name_of_a_file', ), ); ``` -------------------------------- ### SharedPreferencesAsync Operations Source: https://pub.dev/packages/shared_preferences Demonstrates asynchronous operations for setting, getting, and removing data using SharedPreferencesAsync. It also shows how to clear entries with an allow list. ```dart final asyncPrefs = SharedPreferencesAsync(); await asyncPrefs.setBool('repeat', true); await asyncPrefs.setString('action', 'Start'); final bool? repeat = await asyncPrefs.getBool('repeat'); final String? action = await asyncPrefs.getString('action'); await asyncPrefs.remove('repeat'); // Any time a filter option is included as a method parameter, strongly consider // using it to avoid potentially unwanted side effects. await asyncPrefs.clear(allowList: {'action', 'repeat'}); ``` -------------------------------- ### Import shared_preferences_linux in Dart Source: https://pub.dev/packages/shared_preferences_linux/install Import the shared_preferences_linux package into your Dart code to start using its functionalities. ```dart import 'package:shared_preferences_linux/shared_preferences_linux.dart'; ``` -------------------------------- ### Import shared_preferences_android in Dart Source: https://pub.dev/packages/shared_preferences_android/install Import the package into your Dart code to start using its functionalities. ```dart import 'package:shared_preferences_android/shared_preferences_android.dart'; ``` -------------------------------- ### Add shared_preferences_linux to pubspec.yaml Source: https://pub.dev/packages/shared_preferences_linux/install This is an example of how the shared_preferences_linux dependency will appear in your pubspec.yaml file after running `flutter pub add`. ```yaml dependencies: shared_preferences_linux: ^2.4.1 ``` -------------------------------- ### Flutter SharedPreferences Counter Example Source: https://pub.dev/packages/shared_preferences_foundation/example This Flutter code demonstrates a simple counter application that uses SharedPreferences to persist the count across app launches. It initializes the counter on startup and increments it when a button is pressed. ```dart // Copyright 2013 The Flutter Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:shared_preferences_foundation/shared_preferences_foundation.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({super.key}); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State { final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; SharedPreferencesAsyncFoundationOptions options = SharedPreferencesAsyncFoundationOptions(); static const String _counterKey = 'counter'; late Future _counter; Future _incrementCounter() async { final int? value = await _prefs!.getInt(_counterKey, options); final int counter = (value ?? 0) + 1; setState(() { _counter = _prefs.setInt(_counterKey, counter, options).then((_) { return counter; }); }); } Future _getAndSetCounter() async { setState(() { _counter = _prefs!.getInt(_counterKey, options).then((int? counter) { return counter ?? 0; }); }); } @override void initState() { super.initState(); _getAndSetCounter(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('SharedPreferences Demo')), body: Center( child: FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const CircularProgressIndicator(); case ConnectionState.active: case ConnectionState.done: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } }, ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Android Options for SharedPreferencesAsync Source: https://pub.dev/packages/shared_preferences Configure SharedPreferencesAsync on Android to use either DataStore Preferences (default) or SharedPreferences. This example shows how to specify the SharedPreferences backend and an original SharedPreferences file name. ```dart import 'package:shared_preferences_android/shared_preferences_android.dart'; const SharedPreferencesAsyncAndroidOptions options = SharedPreferencesAsyncAndroidOptions( backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( fileName: 'the_name_of_a_file', ), ); ``` -------------------------------- ### Migrate Legacy SharedPreferences to Async/WithCache Source: https://pub.dev/packages/shared_preferences Shows how to use the migration utility to transition from legacy SharedPreferences to SharedPreferencesAsync or SharedPreferencesWithCache. Ensure the migrationCompletedKey is not altered. ```dart import 'package:shared_preferences/util/legacy_to_async_migration_util.dart'; // ··· const sharedPreferencesOptions = SharedPreferencesOptions(); final SharedPreferences prefs = await SharedPreferences.getInstance(); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: prefs, sharedPreferencesAsyncOptions: sharedPreferencesOptions, migrationCompletedKey: 'migrationCompleted', ); ``` -------------------------------- ### Write Data using SharedPreferences Source: https://pub.dev/packages/shared_preferences Demonstrates how to obtain an instance of SharedPreferences and write various data types (int, bool, double, String, List) to it. Use this for simple key-value storage where critical data persistence is not a concern. ```dart // 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', ['Earth', 'Moon', 'Sun']); ``` -------------------------------- ### Initialize SharedPreferences with Cache Options Source: https://pub.dev/packages/shared_preferences/example Creates an instance of SharedPreferencesWithCache, specifying cache options like an allow list for keys. This is useful for performance optimization by caching specific values. ```dart final Future _prefs = SharedPreferencesWithCache.create( cacheOptions: const SharedPreferencesCacheOptions( // This cache will only accept the key 'counter'. allowList: {'counter'}, ), ); ``` -------------------------------- ### Process Exited Successfully Source: https://pub.dev/packages/shared_preferences_ios/score/log.txt Indicates that a process related to Shared Preferences has completed without errors. ```text Execution of process exited 0 STOPPED: 2026-06-02T00:03:51.259085Z ``` -------------------------------- ### Import shared_preferences in Dart Source: https://pub.dev/packages/shared_preferences/install Import the shared_preferences package into your Dart code to start using its functionalities for reading and writing key-value pairs. ```dart import 'package:shared_preferences/shared_preferences.dart'; ``` -------------------------------- ### Get External Integer Preference Source: https://pub.dev/packages/shared_preferences/example Retrieves an integer value for 'externalCounter' from SharedPreferences asynchronously. This is useful for scenarios where preferences might be modified by other parts of the application or system. ```dart Future _getExternalCounter() async { final prefs = SharedPreferencesAsync(); final int externalCounter = (await prefs.getInt('externalCounter')) ?? 0; setState(() { _externalCounter = externalCounter; }); } ``` -------------------------------- ### Import shared_preferences_foundation in Dart Source: https://pub.dev/packages/shared_preferences_foundation/install Import the package into your Dart files to access its functionalities. This line should be placed at the top of your Dart file. ```dart import 'package:shared_preferences_foundation/shared_preferences_foundation.dart'; ``` -------------------------------- ### Add shared_preferences_platform_interface to Flutter Project Source: https://pub.dev/packages/shared_preferences_platform_interface/install Use this command to add the package as a dependency in your pubspec.yaml file. ```bash $ flutter pub add shared_preferences_platform_interface ``` -------------------------------- ### Analyze lib/src/messages.g.dart Source: https://pub.dev/packages/shared_preferences_android/score This snippet shows an example of a static analysis warning related to angle brackets being interpreted as HTML. To reproduce, ensure you are using lints_core and run `flutter analyze lib/src/messages.g.dart`. ```dart ╷ 224 │ /// Adds property to shared preferences data set of type List. │ ^^^^^^^^ ╵ ``` -------------------------------- ### Import shared_preferences_platform_interface in Dart Source: https://pub.dev/packages/shared_preferences_platform_interface/install Import the package into your Dart files to use its functionalities. ```dart import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; ``` -------------------------------- ### Migrate Legacy SharedPreferences to Async Source: https://pub.dev/packages/shared_preferences/example Migrates legacy SharedPreferences data to the new asynchronous API. This ensures compatibility and allows leveraging the modern features of the SharedPreferences package. The migration is marked as completed using a specific key. ```dart // #docregion migrate const sharedPreferencesOptions = SharedPreferencesOptions(); final SharedPreferences prefs = await SharedPreferences.getInstance(); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: prefs, sharedPreferencesAsyncOptions: sharedPreferencesOptions, migrationCompletedKey: 'migrationCompleted', ); // #enddocregion migrate ``` -------------------------------- ### Add shared_preferences_windows Dependency Source: https://pub.dev/packages/shared_preferences_windows/install Run this command to add the package to your Flutter project's dependencies. This will automatically update your pubspec.yaml file. ```bash $ flutter pub add shared_preferences_windows ``` -------------------------------- ### Read Data from SharedPreferences Source: https://pub.dev/packages/shared_preferences Demonstrates how to read various data types (int, bool, double, String, List) from SharedPreferences. If a key does not exist, it returns null. ```dart // Try reading data from the 'counter' key. If it doesn't exist, returns null. final int? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. final bool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. final double? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. final String? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. final List? items = prefs.getStringList('items'); ``` -------------------------------- ### Add shared_preferences_ios to Flutter Project Source: https://pub.dev/packages/shared_preferences_ios/install Use this command to add the package as a dependency. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add shared_preferences_ios ``` -------------------------------- ### Add shared_preferences_linux Dependency Source: https://pub.dev/packages/shared_preferences_linux/install Run this command to add the shared_preferences_linux package to your Flutter project. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add shared_preferences_linux ``` -------------------------------- ### SharedPreferences Demo App Source: https://pub.dev/packages/shared_preferences_ios/example This is the main Dart file for a Flutter application demonstrating the use of shared_preferences_ios. It shows how to increment a counter and persist its value. ```dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({Key? key}) : super(key: key); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State { final SharedPreferencesStorePlatform _prefs = SharedPreferencesStorePlatform.instance; late Future _counter; // Includes the prefix because this is using the platform interface directly, // but the prefix (which the native code assumes is present) is added by the // app-facing package. static const String _prefKey = 'flutter.counter'; Future _incrementCounter() async { final Map values = await _prefs.getAll(); final int counter = ((values[_prefKey] as int?) ?? 0) + 1; setState(() { _counter = _prefs.setValue('Int', _prefKey, counter).then((bool success) { return counter; }); }); } @override void initState() { super.initState(); _counter = _prefs.getAll().then((Map values) { return (values[_prefKey] as int?) ?? 0; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SharedPreferences Demo'), ), body: Center( child: FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return const CircularProgressIndicator(); default: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } })), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Add shared_preferences_foundation Dependency Source: https://pub.dev/packages/shared_preferences_foundation/install Use this command to add the package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file and fetches the package. ```bash $ flutter pub add shared_preferences_foundation ``` -------------------------------- ### Add shared_preferences Dependency Source: https://pub.dev/packages/shared_preferences/install Run this command to add the shared_preferences package to your Flutter project. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add shared_preferences ``` -------------------------------- ### Build UI with FutureBuilder for Initialization Source: https://pub.dev/packages/shared_preferences/example Uses a FutureBuilder to display a CircularProgressIndicator while SharedPreferences are being initialized or data is being fetched. Once the data is ready, it displays the counter value or an error message. ```dart FutureBuilder( future: _counter, builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const CircularProgressIndicator(); case ConnectionState.active: case ConnectionState.done: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data ?? 0 + _externalCounter} time${(snapshot.data ?? 0 + _externalCounter) == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } }, ) ``` -------------------------------- ### shared_preferences_macos License Text Source: https://pub.dev/packages/shared_preferences_macos/license This is the full license text for the shared_preferences_macos package. It outlines the terms of use, modification, and distribution. ```text Copyright 2013 The Flutter Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` -------------------------------- ### Analyze lib/src/messages.g.dart (Second Instance) Source: https://pub.dev/packages/shared_preferences_android/score This snippet is another instance of a static analysis warning concerning angle brackets interpreted as HTML. The reproduction steps are the same: use lints_core and run `flutter analyze lib/src/messages.g.dart`. ```dart ╷ 257 │ /// Adds property to shared preferences data set of type List. │ ^^^^^^^^ ╵ ```