Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Flutter - Local Data Storage

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:
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^latest_version
 

Run 'flutter pub get' to fetch the package. Ensure you replace '^latest_version' with the latest version available on pub.dev.

Step 2: Import the 'shared_preferences' Package

In your Dart code, import the 'shared_preferences' package:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
 

Step 3: Storing and Retrieving Data

Here's how to store and retrieve data using SharedPreferences:

Storing Data:
Future saveData(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
}
 
Retrieving Data:
Future fetchData(String key) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(key) ?? ''; // Default value if key doesn't exist
}
 
Example: Storing and Retrieving User Preferences
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  final _controller = TextEditingController();
  String _savedValue = '';

  @override
  void initState() {
    super.initState();
    _loadSavedValue();
  }

  Future _loadSavedValue() async {
    final value = await fetchData('my_key');
    setState(() {
      _savedValue = value;
      _controller.text = _savedValue;
    });
  }

  void _saveValue() async {
    final value = _controller.text;
    await saveData('my_key', value);
    setState(() {
      _savedValue = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SharedPreferences Example'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(labelText: 'Enter a value'),
            ),
            ElevatedButton(
              onPressed: _saveValue,
              child: Text('Save'),
            ),
            Text('Saved Value: $_savedValue'),
          ],
        ),
      ),
    );
  }
}
 

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:
dependencies:
  flutter:
    sdk: flutter
  sqflite: ^latest_version
 

Run 'flutter pub get' to fetch the package. Replace '^latest_version' with the latest version available on pub.dev.

Step 2: Import the 'sqflite' Package

In your Dart code, import the 'sqflite' package:
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
 

Step 3: Creating and Managing the Database

Here's how to create and manage an SQLite database:

Creating the Database:
final database = await openDatabase(
  'my_database.db',
  version: 1,
  onCreate: (Database db, int version) async {
    // Create tables and schema here
  },
);
 
Creating Tables:
await database.execute('''
  CREATE TABLE my_table (
    id INTEGER PRIMARY KEY,
    name TEXT,
    age INTEGER
  )
''');
 
Inserting Data:
await database.insert('my_table', {
  'name': 'John',
  'age': 30,
});
 
Querying Data:
final List> rows =
    await database.query('my_table', where: 'age > ?', whereArgs: [25]);
 
Example: Creating and Querying a SQLite Database
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> rows = await database.query('my_table');
  for (final row in rows) {
    print('Name: ${row['name']}, Age: ${row['age']}');
  }
}
 

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.