Flutter University
  • πŸ‘‹Welcome to Flutter University
  • Learn Flutter
    • πŸš—Basics
      • 🧺Dart Basics
      • πŸš›Setup & Installation
      • 🐣Hello Flutter
      • πŸŒ‰Widgets
      • ⛸️Basic State Management
      • πŸ‡ΎπŸ‡ΉBasic Layout and Styling
      • 🐝Basic Interactivity
      • πŸ›£οΈNavigation
      • πŸͺ„Working with Assets
    • πŸš…Intermediate
      • 🎯Deeper into Dart
      • ⭐More on State Management
      • πŸ“ƒForm Handling
      • πŸ—ΌNetworking
      • πŸŽ‡Persistence
      • πŸ§™β€β™‚οΈAnimations
      • πŸ§ͺTesting
      • πŸ“¦Package Management
    • ✈️Professional
      • πŸŽ“Advanced Animations
      • 🎨Custom Painters
      • 🐼Continuous Integration/Continuous Deployment (CI/CD)
      • 🎭Performance Profiling
      • πŸ”¬Native Integrations
      • 🌍Accessibility and Localization
      • 🀘Understanding Design Patterns
      • πŸ“šFlutter Architecture
        • The Layer Model
        • Reactive User Interfaces
        • Flutter Widgets
        • The Rendering Process
        • Platform Embedders Overview
        • Integrating with Other Code
        • Support for the Web
  • Tutorials
    • 🌈UI
      • 🏚️Clubhouse Clone
      • πŸ”‰Netflix Clone
    • βš”οΈFull Stack
    • ⛓️Blockchain
    • πŸ€–AI/ML
  • Miscellaneous
    • πŸ–₯️100 Days of Flutter
    • 🎨Join Community
Powered by GitBook
On this page
  • 1. Shared Preferences πŸ”„
  • Setup:
  • Usage:
  • 2. SQLite with sqflite πŸ—„οΈ
  • Setup:
  • Usage:
  • Complete Example Code πŸ“œ
  • Assignments πŸ“

Was this helpful?

  1. Learn Flutter
  2. Intermediate

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'),
          ],
        ),
      ),
    );
  }
}

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

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

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

class SQLiteExample extends StatefulWidget {
  @override
  _SQLiteExampleState createState() => _SQLiteExampleState();
}

class _SQLiteExampleState extends State<SQLiteExample> {
  final _nameController = TextEditingController();
  Database? _database;
  List<Map<String, dynamic>> _users = [];

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

  Future<void> _addUser() async {
    await _database?.insert('Users', {'name': _nameController.text});
    _loadUsers();
  }

  Future<void> _loadUsers() async {
    final users = await _database?.query('Users');
    setState(() {
      _users = users ?? [];
    });
  }

  @override
  void initState() {
    super.initState();
    _initDatabase().then((_) => _loadUsers());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SQLite 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: _addUser,
              child: Text('Add User'),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _users.length,
                itemBuilder: (context, index) {
                  final user = _users[index];
                  return ListTile(
                    title: Text(user['name'] ?? ''),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Assignments πŸ“

Last updated 1 year ago

Was this helpful?

πŸš…
πŸŽ‡