一直在尝试实现简单的费用跟踪应用程序并让自己陷入依赖关系。在空安全删除行很容易之前,现在我必须使用 """companions""" 并且它们的概念对我来说有点不直观。我一直在尝试升级这个应用程序作为 mvvm 在颤振中的学习尝试(有点无用的知识)(https://github.com/musabagab/Money-Manager-Expenses-tracker-app)
Pre-ambula:他们做了 NBBD,现在自动增量 id 参数被标记为必需,我不知道如何在不知道所述 ID 的情况下实现删除。Moor 文档对示例没有帮助,我想按 ID 删除\以他们打算这样做的任何方式(https://drift.simonbinder.eu/docs/getting-started/writing_queries/#updates-and-deletes)
在 null-safety db 代码看起来像这样 + 生成文件之前,插入\删除工作得很好:
import 'package:moor_flutter/moor_flutter.dart';
part 'moor_database.g.dart';
class Transactions extends Table {
TextColumn get type => text()(); //expense /income
IntColumn get id => integer().autoIncrement()();
IntColumn get amount => integer()(); // 300 or 200
}
@UseMoor(tables: [Transactions], daos: [TransactionDao])
class AppDatabase extends _$AppDatabase {
AppDatabase()
: super(FlutterQueryExecutor.inDatabaseFolder(
path: "db.sqlite", logStatements: true));
int get schemaVersion => 1;
}
// Denote which tables this DAO can access
@UseDao(
tables: [Transactions],
queries: {
// this method will be generated
'getTransactionForMonth': 'SELECT * FROM transactions WHERE month = :month',
'sumTheMoneyForMonth':
'SELECT SUM(amount) FROM transactions WHERE month = :month AND type = :type'
},
)
class TransactionDao extends DatabaseAccessor<AppDatabase>
with _$TransactionDaoMixin {
final AppDatabase db;
// Called by the AppDatabase class
TransactionDao(this.db) : super(db);
Future insertTransaction(Transaction transaction) =>
into(transactions).insert(transaction);
Future deleteTransaction(Transaction transaction) =>
delete(transactions).delete(transaction);
}
和数据库服务
import 'package:finances/core/database/moor_database.dart';
class MoorDatabaseService {
final AppDatabase _database = AppDatabase();
getAllTransactions(String month) async {
List<Transaction> allTrans = List<Transaction>();
TransactionDao transactionDao = _database.transactionDao;
allTrans = await transactionDao.getTransactionForMonth(month).get();
return allTrans;
}
Future deleteTransaction(Transaction transaction) async {
return await _database.transactionDao.deleteTransaction(transaction);
}
Future insertTransaction(Transaction transaction) async {
return await _database.transactionDao.insertTransaction(transaction);
}
插入模型(是的,颤振中的 mvvm 哈哈)
class InsertTransactionModel extends BaseModel {
TextEditingController memoController = TextEditingController();
TextEditingController amountController = TextEditingController();
final MoorDatabaseService _moorDatabaseService =
locator<MoorDatabaseService>();
<code skipped>
Transaction newTransaction = new Transaction(
type: type,
day: selectedDay,
month: selectedMonth,
memo: memoController.text,
amount: int.parse(amount),
categoryindex: cateogryIndex);
// insert it!
await _moorDatabaseService.insertTransaction(newTransaction);
Toast.show("Added successfully!", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
// return to the home
Navigator.of(context)
.pushNamedAndRemoveUntil('home', (Route<dynamic> route) => false);
}
}
插入视图模型
class InsertTranscationView extends StatelessWidget {
final Category category;
final int selectedCategory;
InsertTranscationView(this.category, this.selectedCategory);
@override
Widget build(BuildContext context) {
return BaseView<InsertTransactionModel>(
onModelReady: (model) => model.init(selectedCategory, category.index),
builder: (context, model, child) => Scaffold(
appBar: AppBar(
title: selectedCategory == 1 ? Text('Income') : Text('Expense'),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: <Widget>[
ListTile(
**<code skipped>**
Align(
alignment: Alignment.centerLeft,
child: RaisedButton(
child: Text(
'ADD',
style: TextStyle(fontSize: 16),
),
color: backgroundColor,
textColor: Colors.black,
**onPressed: () async {
await model.addTransaction(context);**
},
),
)
],
),
),
),
),
);
}
}
修复 NULL 安全插入##
这是最容易的部分。
final newTransaction = TransactionsCompanion(
type: Value.ofNullable(type),
day: Value.ofNullable(selectedDay),
month: Value.ofNullable(selectedMonth),
memo: Value.ofNullable(memoController.text),
amount: Value.ofNullable(int.parse(amount)),
categoryindex: Value.ofNullable(categoryIndex));
// insert it!
await _databaseService.insertTransaction(newTransaction);
并在服役
Future<int> insertTransaction(TransactionsCompanion transaction) async {
return await _database.transactionDao.insertTransaction(transaction);
}
并在数据库中
Future<int> insertTransaction(TransactionsCompanion transaction) =>
into(transactions).insert(transaction);
删除有点难
我尝试修复空错误:
在删除模型中
Future deleteTransacation(Transaction transaction) async {
final newTransaction = TransactionsCompanion(
type: Value.ofNullable(transaction.type),
day: Value.ofNullable(transaction.day),
month: Value.ofNullable(transaction.month),
memo: Value.ofNullable(transaction.memo),
amount: Value.ofNullable(transaction.amount),
categoryindex: Value.ofNullable(transaction.categoryindex));
// delet it!
return await _databaseService.deleteTransaction(newTransaction);
}
和服务
Future deleteTransaction(TransactionsCompanion transaction) async {
return await _database.transactionDao.deleteTransaction(transaction);
}
和数据库
Future deleteTransaction(TransactionsCompanion transaction) =>
delete(transactions).delete(transaction);
我想数据库本身的删除方法是错误的,因为插入工作没有问题。我尝试组装 TransactionCompanion 并将其作为参数传递给数据库服务,以便它通过 1:1 比较删除相同的事务,我猜?
感谢您的努力!