Flutter Isar 记账应用示例:添加消费记录并显示列表
import 'package:flutter/material.dart'; import 'package:isar/isar.dart'; import 'package:isar_example/isar.g.dart';
@IsarCollection() class Expense { @IsarPrimaryKey() late int id;
String? name; double? amount;
Expense(this.name, this.amount); }
void main() async { WidgetsFlutterBinding.ensureInitialized(); await openIsar(); runApp(MyApp()); }
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Expense Tracker', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } }
class MyHomePage extends StatefulWidget { MyHomePage({Key? key}) : super(key: key);
@override _MyHomePageState createState() => _MyHomePageState(); }
class _MyHomePageState extends State
late IsarCollection
@override
void initState() {
super.initState();
_expenseCollection = isar.getCollection
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Expense Tracker'),
),
body: ListView.builder(
itemCount: _expenses.length,
itemBuilder: (context, index) {
final expense = _expenses[index];
return ListTile(
title: Text(expense.name ?? ''),
subtitle: Text('₹${expense.amount}'),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add Expense'),
content: Column(
mainAxisSize: MainAxisSize.min,
children:
if (name.isNotEmpty && amount != null) {
final expense = Expense(name, amount);
_expenseCollection.put(expense);
setState(() {
_expenses.add(expense);
});
}
Navigator.of(context).pop();
},
),
],
);
},
);
},
tooltip: 'Add Expense',
child: Icon(Icons.add),
),
);
} }
原文地址: https://www.cveoy.top/t/topic/mwgu 著作权归作者所有。请勿转载和采集!