Flutter Local Storage
This section introduces local storage solutions in Flutter, including SharedPreferences, file storage, and SQLite database.
SharedPreferences - lightweight storage
SharedPreferences is suitable for storing simple key-value data.
Add Dependency
dependencies:
shared_preferences: ^2.0.0
Example: SharedPreferences usage
import
'package:shared_preferences/shared_preferences.dart'
;
// Save data
Future
<
void
saveData
(
)
async
{
final
prefs
=await SharedPreferences.
getInstance
(
)
;
// Save a string
await prefs.
setString
(
'username'
,
'Zhang San'
)
;
// Save an integer
await prefs.
setInt
(
'age'
,
25
)
;
// Save a boolean
await prefs.
setBool
(
'isLoggedIn'
,
true
)
;
// Save a list (JSON string)
await prefs.
setStringList
(
'tags'
,
[
'flutter'
,
'dart'
]
)
;
}
// Read data
Future
<
void
loadData
(
)
async
{
final
prefs
=await SharedPreferences.
getInstance
(
)
;
final
username
=
prefs.
getString
(
'username'
)
??
''
;
final
age
=
prefs.
getInt
(
'age'
)
??
0
;
final
isLoggedIn
=
prefs.
getBool
(
'isLoggedIn'
)
??
false
;
final
tags
=
prefs.
getStringList
(
'tags'
)
??
[
]
;
(
'Username: $username'
)
;
(
'Age: $age'
)
;
(
'Logged in: $isLoggedIn'
)
;
(
'Tags: $tags'
)
;
}
// Delete data
Future
<
void
deleteData
(
)
async
{
final
prefs
=await SharedPreferences.
getInstance
(
)
;
// Delete a single item
await prefs.
remove
(
'username'
)
;
// Delete all
await prefs.
clear
(
)
;
}
File storage
Use path_provider to obtain the app's documents directory for file storage.
Add Dependency
dependencies:
path_provider: ^2.0.0
Example: file read and write
import
'dart:io'
;
import
'package:path_provider/path_provider.dart'
;
// Get the documents directory
Future
<
Directory
get_documentDirectory async
{
return
await getApplicationDocumentsDirectory
(
)
;
}
// Write to a file
Future
<
void
writeFile
(
)
async
{
final
dir
=await _documentDirectory
;
final
file
=
File
(
'${dir.path}/my_file.txt'
)
;
// Write text
await file.
writeAsString
(
'Hello Flutter!'
)
;
// Write bytes
final
bytes
=
[
72
,
101
,
108
,
108
,
111
]
;
// "Hello"
await file.
writeAsBytes
(
bytes
)
;
}
// Read the file
Future
<
void
readFile
(
)
async
{
final
dir
=await _documentDirectory
;
final
file
=
File
(
'${dir.path}/my_file.txt'
)
;
if
(
await file.
exists
(
)
)
{
// Read text
final
content
=
await file.
readAsString
(
)
;
(
'File content: $content'
)
;
// Read bytes
final
bytes
=
await file.
readAsBytes
(
)
;
(
'Bytes: $bytes'
)
;
}
}
// JSON file storage
Future
<
void
saveJson
(
)
async
{
final
dir
=await _documentDirectory
;
final
file
=
File
(
'${dir.path}/data.json'
)
;
final
data
=
{
'name'
:
'Zhang San'
,
'age'
:
25
,
'skills'
:
[
'Flutter'
,
'Dart'
]
,
}
;
// Use jsonEncode to save JSON
await file.
writeAsString
(
jsonEncode
(
data
)
)
;
}
SQLite database
Use sqflite for SQLite database operations.
Add Dependency
dependencies:
sqflite: ^2.0.0
path: ^1.8.0
Example: basic SQLite operations
import
'package:sqflite/sqflite.dart'
;
import
'package:path/path.dart'
;
// Database helper class
class
DatabaseHelper
{
static
final
DatabaseHelper instance
=
DatabaseHelper._init
(
)
;
static
Database
?
_database
;
DatabaseHelper._init
(
)
;
Future
<
Database
getdatabase async
{
if
(
_database
!=
null
)
return
_database
!
;
_database
=
await _initDB
(
'my_app.db'
)
;
return
_database
!
;
}
// Initialize the database
Future
<
Database
_initDB
(String filePath
)
async
{
final
dbPath
=
await getDatabasesPath
(
)
;
final
path
=
join
(
dbPath
,
filePath
)
;
return
await openDatabase
(
path
,
version
:
1
,
onCreate
:
_createDB
,
)
;
}
// Create table
Future
<
void
_createDB
(Database db
,
int
version
)
async
{
await db.
execute
(
''
'
CREATE TABLE users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
age INTEGER
)
'
''
)
;
}
// Insert data
Future
<
int
insertUser
(
Map
<
String
,
dynamic
user
)
async
{
final
db
=await database
;
return
await db.
insert
(
'users'
,
user
)
;
}
// Query all users
Future
<
List
<
Map
<
String
,
dynamic
getAllUsers
(
)
async
{
final
db
=await database
;
return
await db.
query
(
'users'
)
;
}
// Conditional query
Future
<
List
<
Map
<
String
,
dynamic
getUserByName
(String name
)
async
{
final
db
=
await database
;
return
await db.
query
(
'users'
,
where
:
'name = ?'
,
whereArgs
:
[
name
]
,
)
;
}
// Update data
Future
<
int
updateUser
(
int
id
,
Map
<
String
,
dynamic
user
)
async
{
final
db
=await database
;
return
await db.
update
(
'users'
,
user
,
where
:
'id = ?'
,
whereArgs
:
[
id
]
,
)
;
}
// Delete data
Future
<
int
deleteUser
(
int
id
)
async
{
final
db
=await database
;
return
await db.
delete
(
'users'
,
where
:
'id = ?'
,
whereArgs
:
[
id
]
,
)
;
}
// Close the database
Future
<
void
close
(
)
async
{
final
db
=await database
;
db.
close
(
)
;
}
}
// Usage example
Future
<
void
dbExample
(
)
async
{
final
db
=DatabaseHelper.
instance
;
// Add a user
await db.
insertUser
(
{
'name'
:
'Zhang San'
,
'email'
:
'zhangsan@example.com'
,
'age'
:
25
,
}
)
;
// Query all
final
users
=
await db.
getAllUsers
(
)
;
(
'User list: $users'
)
;
// Update a user
await db.
updateUser
(
1
,
{
'name'
:
'Li Si'
,
'age'
:
30
}
)
;
// Delete a user
await db.
deleteUser
(
1
)
;
}
Data storage solution selection: use SharedPreferences for simple key-value data, SQLite for complex structures, and file storage for large files.