19. Local Data Storage (SharedPreferences, SQLite)
Local data storage is essential for persisting data in Flutter applications. Flutter offers two primary methods for local data storage: SharedPreferences for key-value storage and SQLite for more complex relational database storage. In this tutorial, we'll explore both methods and provide examples for each.
1.Using SharedPreferences
SharedPreferences is a simple key-value storage solution that's suitable for storing small amounts of data, such as user preferences and settings.
Step 1: Add the 'shared_preferences' Package
In your 'pubspec.yaml' file, add the 'shared_preferences' package as a dependency:
In this example, we create a simple Flutter app that allows users to enter a value and save it to SharedPreferences. The saved value is retrieved when the app starts, allowing users to see their previously saved data.
2.Using SQLite
SQLite is a more advanced local storage solution suitable for storing structured data in relational database format. Flutter provides the 'sqflite' package to interact with SQLite databases.
Step 1: Add the 'sqflite' Package
In your 'pubspec.yaml' file, add the 'sqflite' package as a dependency:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final database = await openDatabase('my_database.db', version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
CREATE TABLE my_table (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''');
});
await database.insert('my_table', {
'name': 'Alice',
'age': 28,
});
final List
In this example, we create a SQLite database, define a table ('my_table'), and insert a record into it. We then query the table and print the results.
Conclusion:
Local data storage is essential for maintaining and persisting data in Flutter applications. SharedPreferences provides a straightforward key-value store for simple data, while SQLite offers a more complex relational database solution for structured data. Depending on your app's requirements, you can choose the appropriate local data storage method.