From 5561f50736cc41f080b16a188fbf2060261b47ab Mon Sep 17 00:00:00 2001 From: Hyperling Date: Wed, 5 Feb 2025 14:43:06 -0700 Subject: [PATCH] Begin working on the database. --- lib/db.dart | 45 ++++++++++++++++++++++++++++++++++++++++++ lib/main.dart | 7 ++++--- lib/pages/expense.dart | 3 +++ 3 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 lib/db.dart diff --git a/lib/db.dart b/lib/db.dart new file mode 100644 index 0000000..469479a --- /dev/null +++ b/lib/db.dart @@ -0,0 +1,45 @@ +// 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, + ); +} diff --git a/lib/main.dart b/lib/main.dart index 6e80a13..ebcb292 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,15 +1,16 @@ -// Helpful guides: -// - https://flutter.dev/docs/cookbook/forms/validation - +// Flutter import 'package:flutter/material.dart'; +// Local import '/pages/expense.dart'; import '/pages/income.dart'; import '/pages/asset.dart'; import '/pages/report.dart'; import '/pages/settings.dart'; +import '/db.dart'; void main() { + loadDB(); runApp(const MainApp()); } diff --git a/lib/pages/expense.dart b/lib/pages/expense.dart index d3b4f47..2a383c1 100644 --- a/lib/pages/expense.dart +++ b/lib/pages/expense.dart @@ -1,5 +1,7 @@ +// Flutter import 'package:flutter/material.dart'; +// Local import '/models/expense.dart'; import '/models/frequency.dart'; @@ -61,6 +63,7 @@ class _ExpenseInputDialogState extends State { @override Widget build(BuildContext context) { + // TODO: Do this as a values.map(). List freqValues = []; for (var freq in Frequency.values) { freqValues.add(DropdownMenuItem(value: freq, child: Text(freq.title)));