To persist data efficiently in Flutter using a local database, such as SQLite
, is the way to go:
- Import the right dependecies:
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
- Open the DB:
WidgetsFlutterBinding.ensureInitialized();
// Open the database and store the reference.
final Future<Database> database = openDatabase(
join(await getDatabasesPath(), 'recipes_database.db'),
);
- Create the table:
final Future<Database> database = openDatabase(
join(await getDatabasesPath(), 'doggie_database.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TITLE)", // all the properties here
);
},
version: 1,
);
- Create methods to insert and retrieve entries:
Future<void> inserRecipe(Recipe recipe) async {
final Database db = await database;
await db.insert(
'recipe',
recipe.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Recipe>> recipes() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('recipes');
return List.generate(maps.length, (i) {
return Recipe(
title: maps[i]['title'],
// ... all the properties here
);
});
}
Since our class, Recipe
, contains files, and more specifically images, we could store the Image
as an URL
and take advantage of the Cache
to retrieve it:
var image = await DefaultCacheManager().getSingleFile(recipe.picture);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…