logologo
  • AI Interviewer
  • Features
  • Jobs
  • AI Tools
  • FAQs
logologo

Transform your hiring process with AI-powered interviews. Screen candidates faster and make better hiring decisions.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • AI Pre-Screening

Procodebase © 2025. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Local Storage in Flutter

author
Generated by
Nitish Kumar Singh

21/09/2024

Flutter

Sign in to read full article

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: Simple Key-Value Storage

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.

How to Use Shared Preferences in Flutter

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.

Basic Example of Shared Preferences

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 { @override Widget build(BuildContext context) { return MaterialApp( home: PreferenceDemo(), ); } } class PreferenceDemo extends StatefulWidget { @override _PreferenceDemoState createState() => _PreferenceDemoState(); } class _PreferenceDemoState extends State<PreferenceDemo> { TextEditingController _controller = TextEditingController(); String _storedValue = ''; @override 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(); } @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: [ 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.

SQLite: Local Database Storage

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.

How to Use SQLite in Flutter

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

Basic Example of SQLite

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 { @override Widget build(BuildContext context) { return MaterialApp( home: SQLiteDemo(), ); } } class SQLiteDemo extends StatefulWidget { @override _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']; }); }); } } @override void initState() { super.initState(); _initializeDatabase(); } @override 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.

Popular Tags

FlutterShared PreferencesSQLite

Share now!

Like & Bookmark!

Related Collections

  • Flutter Development: Build Beautiful Apps

    21/09/2024 | Flutter

Related Articles

  • Enhancing User Experience with Animations and Transitions in Flutter

    21/09/2024 | Flutter

  • Introduction to Flutter and Dart

    21/09/2024 | Flutter

  • Deploying Flutter Apps to App Stores

    21/09/2024 | Flutter

  • Testing Flutter Applications

    21/09/2024 | Flutter

  • Integrating Firebase with Flutter

    21/09/2024 | Flutter

  • Exploring Flutter for Web and Desktop

    21/09/2024 | Flutter

  • Understanding Flutter Widgets

    21/09/2024 | Flutter

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design