In Flutter app development, it is often necessary to save and retrieve application data locally. While there are various options available, one popular choice is to use the shared_preferences package. This package provides a simple and efficient way to persist key-value pairs on the user's device.
To get started, add the shared_preferences package to your pubspec.yaml file:
dependencies: flutter: sdk: flutter shared_preferences: <version_number>
Once the package is added, run flutter pub get to fetch the dependencies.
Now, let's see how we can use the shared_preferences package to persist data locally:
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MyPreferencesPage extends StatefulWidget { @override _MyPreferencesPageState createState() => _MyPreferencesPageState(); } class _MyPreferencesPageState extends State{ late SharedPreferences _prefs; late String _savedData; @override void initState() { super.initState(); initSharedPreferences(); } Future initSharedPreferences() async { _prefs = await SharedPreferences.getInstance(); setState(() { _savedData = _prefs.getString('my_data') ?? ''; }); } Future saveData(String data) async { setState(() { _savedData = data; }); await _prefs.setString('my_data', data); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Shared Preferences Example'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Saved Data:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 10), Text( _savedData, style: TextStyle(fontSize: 16), ), SizedBox(height: 20), ElevatedButton( onPressed: () { saveData('Hello, Flutter!'); }, child: Text('Save Data'), ), ], ), ), ); } }
In the above code snippet, we define a MyPreferencesPage widget that utilizes the shared_preferences package. Upon initialization, we fetch the shared preferences instance and retrieve the saved data if available. We also provide a method to save data and update the UI accordingly.
This example demonstrates a simple implementation where we save and display a string value. However, the package supports storing various data types including int, double, bool, and more.
By persisting data locally using the shared_preferences package, you can provide better user experiences by remembering user preferences, settings, or any other data that needs to be stored between app launches.
Summary: The shared_preferences package in Flutter offers a convenient way to persist key-value pairs locally. By adding and retrieving data using this package, you can easily store and retrieve user preferences or any other data that needs to persist within your Flutter application.