我是 Flutter 新手,面临一些困难。 我正在构建一个费用跟踪应用程序并尝试使用 sqflite 包实现一个数据库。但是,每当我尝试添加新事务时,都会收到异常“这将来会引发异常”。目前,它在调试控制台中按类型显示一次,并且应用程序冻结。我是否滥用了回调函数? 相关代码如下:
这是我的数据库定义和操作代码:
class DbUtil {
DbUtil._();
static final DbUtil instance = DbUtil._();
static Database? _database;
get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
return await sql.openDatabase(
path.join(await sql.getDatabasesPath(), 'transactions.db'),
version: 1,
onCreate: _onCreate,
);
}
_onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE transactions (id TEXT PRIMARY KEY, title TEXT, value FLOAT, date DATE ,category TEXT)');
}
Future<void> insert(String table, Map<String, Object> data) async {
final db = await database;
await db.insert(table, data,
conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
}
接下来,我的 main.dart (我删除了一些代码以使其相关内容简洁):
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Expenses',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Category>? category;
final _baseUrl = 'https://expenses-a210d-default-rtdb.firebaseio.com/';
List<Transact> _transactions = [];
_openTransactionFormModal(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (_) {
return TransactionForm(_addTransaction);
},
);
}
_addTransaction(String title, double value, DateTime date, String category) {
final newTransaction = Transact(
id: Random().nextDouble().toString(),
title: title,
value: value,
date: date,
category: category,
);
setState(() {
_transactions.add(newTransaction);
_sumTotalCategory(newTransaction);
_addToDb(newTransaction);
});
Navigator.of(context).pop();
}
_addToDb(transaction) async {
await DbUtil.instance.insert(
'transactions',
{
'id': transaction.id,
'title': transaction.title,
'value': transaction.value,
'date': transaction.date,
'category': transaction.category,
},
);
}
@override
Widget build(BuildContext context) {
final appBar = AppBar(
title: Text(
'Despesas Pessoais',
style: TextStyle(
fontSize: 20 * MediaQuery.of(context).textScaleFactor,
),
),
actions: [
// IconButton(
// onPressed: () => loadTransactions(),
// icon: Icon(Icons.refresh),
// ),
IconButton(
onPressed: () => _openTransactionFormModal(context),
icon: Icon(Icons.add),
),
]);
final availableHeight = MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top;
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
PieChartExpenses(valueSum),
Container(
width: double.infinity,
child: Card(
color: Color.fromARGB(255, 2, 84, 90),
elevation: 5,
child: total_sum(valueSum: valueSum),
),
),
Container(
height: availableHeight * 0.7,
child: Column(
children: [
TransactionList(_transactions, _removeTransaction),
],
),
),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _openTransactionFormModal(context),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
}
我尝试根据这个答案的解决方案修改插入功能,但没有成功。 我也尝试修改之后关闭数据库的函数,但这也没有效果。据我所知,数据库甚至没有被打开。
应用程序冻结后,我尝试重新启动它。调试控制台上出现以下消息:
E/flutter (11237): #24 DbUtil.insert db_util.dart:35
E/flutter (11237): <asynchronous suspension>
E/flutter (11237): #25 _MyHomePageState._addToDb main.dart:109
E/flutter (11237): <asynchronous suspension>
main.dart 上的第 109 行包含 “transactions”,(_addToDB 函数的第三行)。 db_util.dart 中的第 35 行是插入函数上的 await db.insert(table, data,。
在此输入链接描述 Hai Teman dana jika membutuhkan bantuan hubungi kami langsung