Day 21: Working with Local Storage
Harpal Matholiya
Mobile App Developer | Flutter Developer | 3+ Years Experience | Worked on 50+ Projects | 4.7/5 Rating | Building Scalable, User-Centric Apps | Quality-Driven | Innovation-Focused | Committed to Excellence
Topic: Saving Data Locally
Storing data locally on a device is essential for many mobile applications, especially when dealing with user preferences, app settings, or data that needs to persist across sessions. Today, we'll explore different ways to save data locally in a Flutter application.
Why Use Local Storage?
- Offline Access: Data stored locally can be accessed even when the device is offline.
- Improved Performance: Local storage reduces the need for frequent network requests, leading to faster data retrieval.
- User Preferences: Storing user preferences and settings locally enhances the user experience.
Common Local Storage Options in Flutter
- Shared Preferences: Ideal for storing small amounts of simple data such as user preferences.
- SQLite: Suitable for complex structured data that requires a relational database.
- Hive: A lightweight and fast key-value database for Flutter apps.
Using Shared Preferences
Shared Preferences is perfect for storing simple data like user settings.
Step 1: Adding Shared Preferences to Your Project
Add the shared_preferences package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.6
Run flutter pub get to install the package.
Step 2: Saving and Retrieving Data
Create a simple app to demonstrate saving and retrieving data using Shared Preferences.
- Save Data:
领英推è
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
String _savedText = '';
Future<void> _saveText() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('saved_text', _controller.text);
}
Future<void> _getText() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_savedText = prefs.getString('saved_text') ?? 'No data';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Shared Preferences Demo')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(controller: _controller),
SizedBox(height: 20),
ElevatedButton(onPressed: _saveText, child: Text('Save Text')),
SizedBox(height: 20),
ElevatedButton(onPressed: _getText, child: Text('Get Text')),
SizedBox(height: 20),
Text('Saved Text: $_savedText'),
],
),
),
);
}
}
Using SQLite
SQLite is great for structured data storage. Use the sqflite package for SQLite in Flutter.
Step 1: Adding sqflite to Your Project
Add the sqflite and path packages to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
sqflite: ^2.0.0+3
path: ^1.8.0
Run flutter pub get to install the packages.
Step 2: Creating a Database Helper
- Create Database Helper:
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
factory DatabaseHelper() => _instance;
DatabaseHelper._internal();
static Database? _database;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
String path = join(await getDatabasesPath(), 'example.db');
return await openDatabase(
path,
version: 1,
onCreate: (db, version) {
return db.execute(
'CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)',
);
},
);
}
Future<void> insertItem(Map<String, dynamic> item) async {
final db = await database;
await db.insert('items', item, conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<List<Map<String, dynamic>>> getItems() async {
final db = await database;
return await db.query('items');
}
}
- Use Database Helper:
import 'package:flutter/material.dart';
import 'database_helper.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final dbHelper = DatabaseHelper();
List<Map<String, dynamic>> _items = [];
@override
void initState() {
super.initState();
_fetchItems();
}
Future<void> _fetchItems() async {
final items = await dbHelper.getItems();
setState(() {
_items = items;
});
}
Future<void> _addItem(String name) async {
await dbHelper.insertItem({'name': name});
_fetchItems();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SQLite Demo')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(onSubmitted: (value) => _addItem(value)),
SizedBox(height: 20),
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_items[index]['name']),
);
},
),
),
],
),
),
);
}
}
Conclusion
Using local storage in Flutter is essential for providing a seamless user experience and ensuring data persistence. Whether you use Shared Preferences for simple data or SQLite for more complex structured data, Flutter offers robust solutions to meet your needs.
Ready to master Flutter? Join our 30-day development course for just ?5000/month. Learn from experts and build real-world apps. Enroll now! #Flutter #LearnToCode #MobileDevelopment #OpenToWork