46 lines
1.3 KiB
Dart

// https://docs.flutter.dev/cookbook/persistence/sqlite
// SQLite
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter_expense_tracker/models/frequency.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
// Local
import '/models/expense.dart';
void loadDB() async {
// Avoid errors caused by flutter upgrade.
WidgetsFlutterBinding.ensureInitialized();
final String frequencies =
"'${Frequency.values.map((freq) => freq.title).join("','")}'";
print(frequencies);
// Open the database and store the reference.
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'expense_tracker.db'),
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
"""
CREATE TABLE expense
( id INTEGER PRIMARY KEY
, name TEXT
, cost DOUBLE
, frequency TEXT CHECK(frequency IN ($frequencies) )
, description TEXT
)""",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
}