πŸŽ‡Persistence

Data persistence is crucial for maintaining data across app launches. Flutter offers several options for data persistence, and one of the most common is using the shared_preferences package for storing simple data, and the sqflite package for more complex or structured data.

1. Shared Preferences πŸ”„

For simple data storage, shared_preferences is a great choice. It allows you to store simple data in key-value pairs.

Setup:

Add the shared_preferences package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2

Usage:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString('name', 'John Doe');
}

Future<String?> getName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('name');
}

2. SQLite with sqflite πŸ—„οΈ

For more structured data, you might want to use a local database such as SQLite.

Setup:

Add the sqflite and path_provider packages to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.3.0
  path_provider: ^2.1.1

Usage:

import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

Future<Database> getDatabase() async {
  final directory = await getApplicationDocumentsDirectory();
  final path = directory.path + 'app.db';
  return openDatabase(
    path,
    version: 1,
    onCreate: (db, version) {
      db.execute('CREATE TABLE Users(id INTEGER PRIMARY KEY, name TEXT)');
    },
  );
}

Future<void> addUser(String name) async {
  final db = await getDatabase();
  await db.insert('Users', {'name': name});
}

Future<List<Map<String, dynamic>>> getUsers() async {
  final db = await getDatabase();
  return db.query('Users');
}

Complete Example Code πŸ“œ

Here's a simple example demonstrating how to use sqflite or shared_preference for data persistence in Flutter:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

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

class SharedPreferencesExample extends StatefulWidget {
  @override
  _SharedPreferencesExampleState createState() => _SharedPreferencesExampleState();
}

class _SharedPreferencesExampleState extends State<SharedPreferencesExample> {
  final _nameController = TextEditingController();
  String _name = '';

  Future<void> _saveName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('name', _nameController.text);
  }

  Future<void> _loadName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _name = prefs.getString('name') ?? 'No name saved';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Shared Preferences Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: _nameController,
              decoration: InputDecoration(labelText: 'Name'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _saveName,
              child: Text('Save Name'),
            ),
            ElevatedButton(
              onPressed: _loadName,
              child: Text('Load Name'),
            ),
            SizedBox(height: 20),
            Text('Saved Name: $_name'),
          ],
        ),
      ),
    );
  }
}


Assignments πŸ“

Last updated