When developing mobile applications, managing data localization is crucial. Flutter provides developers with multiple options for storing data locally, two of the most commonly used being Shared Preferences and SQLite. Each of these storage solutions has its specific use cases, strengths, and weaknesses. In this article, we’ll delve into how to implement both Shared Preferences and SQLite in your Flutter applications.
Shared Preferences is a lightweight, key-value storage solution well-suited for saving simple data like user settings or preferences. It is particularly useful for storing primitive types (like strings, integers, and booleans) and works seamlessly across sessions.
To get started with Shared Preferences in Flutter, you’ll first need to add the dependency in your pubspec.yaml
file:
dependencies: shared_preferences: ^2.0.0
After saving your changes, run flutter pub get
to install the package.
Here’s a straightforward example that demonstrates how to store, retrieve, and delete data using Shared Preferences.
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: PreferenceDemo(), ); } } class PreferenceDemo extends StatefulWidget { _PreferenceDemoState createState() => _PreferenceDemoState(); } class _PreferenceDemoState extends State<PreferenceDemo> { TextEditingController _controller = TextEditingController(); String _storedValue = ''; void initState() { super.initState(); _loadStoredValue(); } _loadStoredValue() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _storedValue = prefs.getString('storedString') ?? ''; }); } _saveValue() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('storedString', _controller.text); _loadStoredValue(); } _deleteValue() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.remove('storedString'); _loadStoredValue(); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Shared Preferences Example')), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ TextField( controller: _controller, decoration: InputDecoration(labelText: 'Enter a value'), ), ElevatedButton( onPressed: _saveValue, child: Text('Save to Preferences'), ), ElevatedButton( onPressed: _deleteValue, child: Text('Delete from Preferences'), ), SizedBox(height: 20), Text('Stored Value: $_storedValue'), ], ), ), ); } }
In the above example, you can input a value that gets saved in shared preferences when you press the “Save to Preferences” button. The stored value is displayed on the screen, and you can remove it via the “Delete from Preferences” button.
For more complex data storage needs, SQLite is the go-to solution. It allows you to create structured databases, making it ideal for applications that require persistent storage of diverse data types or advanced querying capabilities.
To incorporate SQLite into your Flutter app, you’ll need to add the sqflite
and path
packages to your pubspec.yaml
:
dependencies: sqflite: ^2.0.0 path: ^1.8.0
Here's a basic example to demonstrate how to create a SQLite database, insert data, and retrieve it.
import 'package:flutter/material.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: SQLiteDemo(), ); } } class SQLiteDemo extends StatefulWidget { _SQLiteDemoState createState() => _SQLiteDemoState(); } class _SQLiteDemoState extends State<SQLiteDemo> { Database? _database; List<String> _entries = []; Future<void> _initializeDatabase() async { _database = await openDatabase( join(await getDatabasesPath(), 'entries.db'), onCreate: (db, version) { return db.execute( 'CREATE TABLE entries(id INTEGER PRIMARY KEY AUTOINCREMENT, entry TEXT)', ); }, version: 1, ); _loadEntries(); } Future<void> _addEntry(String entry) async { if (_database != null) { await _database!.insert('entries', {'entry': entry}); _loadEntries(); } } Future<void> _loadEntries() async { if (_database != null) { final List<Map<String, dynamic>> records = await _database!.query('entries'); setState(() { _entries = List.generate(records.length, (i) { return records[i]['entry']; }); }); } } void initState() { super.initState(); _initializeDatabase(); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('SQLite Example')), body: Column( children: [ TextField( onSubmitted: _addEntry, decoration: InputDecoration(labelText: 'Add a new entry'), ), Expanded( child: ListView.builder( itemCount: _entries.length, itemBuilder: (context, index) { return ListTile(title: Text(_entries[index])); }, ), ), ], ), ); } }
In this example, we create a basic SQLite database to manage a list of entries. The app allows you to input new entries, which are stored in the database and displayed in a list.
Local storage in Flutter, whether through Shared Preferences or SQLite, provides significant flexibility to cater to different data needs. Understanding how and when to use these storage options can significantly enhance your application's functionality and user experience.
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter
21/09/2024 | Flutter