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 { final TextEditingController _nameController = TextEditingController(); final TextEditingController _amountController = TextEditingController();

late IsarCollection _expenseCollection; late List _expenses;

@override void initState() { super.initState(); _expenseCollection = isar.getCollection(); _expenses = _expenseCollection.getAllSync(); }

@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: [ TextField( controller: _nameController, decoration: InputDecoration( labelText: 'Name', ), ), TextField( controller: _amountController, keyboardType: TextInputType.number, decoration: InputDecoration( labelText: 'Amount', ), ), ], ), actions: [ TextButton( child: Text('Cancel'), onPressed: () { Navigator.of(context).pop(); }, ), ElevatedButton( child: Text('Add'), onPressed: () { final name = _nameController.text; final amount = double.tryParse(_amountController.text);

                  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),
  ),
);

} }

Flutter Isar 记账应用示例:添加消费记录并显示列表

原文地址: https://www.cveoy.top/t/topic/mwgu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录