import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../database_helper.dart';
class TransactionSummaryBySiteScreen extends StatefulWidget { const TransactionSummaryBySiteScreen({super.key});
@override _TransactionSummaryBySiteScreenState createState() => _TransactionSummaryBySiteScreenState(); }
class _TransactionSummaryBySiteScreenState extends State { List<Map<String, dynamic>> sites = []; int? selectedSiteId; Map<String, dynamic>? summary; bool isLoadingSites = true; bool isLoadingSummary = false;
List<Map<String, dynamic>> previousTransactions = []; bool isLoadingTransactions = false;
DateTime? startDate; DateTime? endDate;
@override void initState() { super.initState(); _loadSites(); }
Future _loadSites() async { final siteList = await DatabaseHelper.instance.getSites(); setState(() { sites = [ {'id': -1, 'name': 'All Sites'}, ...siteList ]; isLoadingSites = false; if (sites.isNotEmpty) { selectedSiteId = sites.first['id']; _loadSummaryForSite(selectedSiteId!); } }); }
Future _loadSummaryForSite(int siteId) async { setState(() { isLoadingSummary = true; isLoadingTransactions = true; summary = null; previousTransactions = []; });
late final Map<String, dynamic> data;
late final List<Map<String, dynamic>> transactions;
if (siteId == -1) {
data = await DatabaseHelper.instance
.getMonthlyTransactionSummaryAllSites(startDate, endDate);
transactions = await DatabaseHelper.instance
.getAllTransactionsFiltered(startDate, endDate);
} else {
data = await DatabaseHelper.instance
.getFullTransactionSummaryBySite(siteId, startDate, endDate);
transactions = await DatabaseHelper.instance
.getTransactionsBySiteFiltered(siteId, startDate, endDate);
}
setState(() {
summary = data;
previousTransactions = transactions;
isLoadingSummary = false;
isLoadingTransactions = false;
});
}
@override Widget build(BuildContext context) { if (isLoadingSites) { return const Center(child: CircularProgressIndicator()); }
return Scaffold(
backgroundColor: const Color(0xFFF1F8E9),
appBar: AppBar(
backgroundColor: Colors.teal,
title: const Text('Transaction Report'),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("Select Site",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
DropdownButtonFormField<int>(
value: selectedSiteId,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
isExpanded: true,
items: sites.map((site) {
return DropdownMenuItem<int>(
value: site['id'],
child: Text(site['name']),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() {
selectedSiteId = value;
});
_loadSummaryForSite(value);
}
},
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: ElevatedButton.icon(
icon: const Icon(Icons.date_range),
label: Text(
startDate == null || endDate == null
? 'Select Date Range'
: '${DateFormat('dd MMM').format(startDate!)} - ${DateFormat('dd MMM').format(endDate!)}',
),
onPressed: () async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2000),
lastDate: DateTime.now(),
initialDateRange: startDate != null && endDate != null
? DateTimeRange(start: startDate!, end: endDate!)
: null,
);
if (picked != null) {
setState(() {
startDate = picked.start;
endDate = picked.end;
});
_loadSummaryForSite(selectedSiteId!);
}
},
),
),
const SizedBox(width: 8),
if (startDate != null || endDate != null)
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
startDate = null;
endDate = null;
});
_loadSummaryForSite(selectedSiteId!);
},
),
],
),
const SizedBox(height: 24),
if (isLoadingSummary)
const Center(child: CircularProgressIndicator())
else if (summary == null)
const Center(child: Text("No data available."))
else
Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Site: ${sites.firstWhere((s) => s['id'] == selectedSiteId, orElse: () => {
'name': 'Unknown'
})['name']}",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.black87),
),
const SizedBox(height: 12),
_buildRow("Total Income:", summary!['totalIncome'],
color: Colors.green),
_buildRow("Total Expense:", summary!['totalExpense'],
color: Colors.red),
const Divider(),
_buildRow("Net Total:", summary!['netTotal'],
color: Colors.blue),
],
),
),
),
const SizedBox(height: 16),
if (selectedSiteId != null)
Expanded(
child: FutureBuilder<List<Map<String, dynamic>>>(
future: DatabaseHelper.instance
.getTransactionsBySiteFiltered(
selectedSiteId!, startDate, endDate),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final transactions = snapshot.data!;
if (transactions.isEmpty) {
return const Text("No previous transactions found.");
}
return ListView(
children: transactions.map((tx) {
final isIncome = tx['type'] == 'income';
final sign = isIncome ? '+' : '-';
final amount = tx['amount'];
return ListTile(
title: Text(
"${tx['type'].toString().toUpperCase()} $sign ₹$amount",
style:
const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Date: ${DateFormat('yyyy-MM-dd').format(DateTime.parse(tx['date']))}',
style: const TextStyle(
fontSize: 14, color: Colors.grey),
),
if (tx['note'] != null &&
tx['note'].toString().trim().isNotEmpty)
Text(
'Note: ${tx['note']}',
style: const TextStyle(
fontSize: 14, color: Colors.black87),
),
Text("Pond: ${tx['pond_name'] ?? 'N/A'}"),
],
),
);
}).toList(),
);
},
),
),
],
),
),
),
);
}
Widget _buildRow(String label, dynamic value, {Color color = Colors.black}) { return Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(label, style: const TextStyle(fontSize: 16)), Text( value is double ? value.toStringAsFixed(2) : value.toString(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color: color), ), ], ), ); } }
Based on your provided code, I noticed a few potential issues and areas for improvement. The main problem is in the transaction list section, where the FutureBuilder is redundantly fetching transactions from the database again, even though the _loadSummaryForSite method already fetches and stores the transactions in the previousTransactions state variable. This can lead to:
selectedSiteId is -1 (for "All Sites"), the FutureBuilder calls getTransactionsBySiteFiltered, which might not handle -1 correctly, potentially causing errors or incorrect results.FutureBuilder might not properly handle changes in selectedSiteId or date range, as it only runs once unless the widget rebuilds.To fix this, I recommend removing the FutureBuilder and directly using the previousTransactions list from the state. This leverages the existing loading logic in _loadSummaryForSite, which already sets isLoadingTransactions and populates previousTransactions. This approach is more efficient and consistent.
Here's the corrected version of your code with the following changes:
FutureBuilder and replaced it with a direct use of previousTransactions.isLoadingTransactions to handle the loading state.import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../database_helper.dart';
class TransactionSummaryBySiteScreen extends StatefulWidget {
const TransactionSummaryBySiteScreen({super.key});
@override
_TransactionSummaryBySiteScreenState createState() =>
_TransactionSummaryBySiteScreenState();
}
class _TransactionSummaryBySiteScreenState
extends State<TransactionSummaryBySiteScreen> {
List<Map<String, dynamic>> sites = [];
int? selectedSiteId;
Map<String, dynamic>? summary;
bool isLoadingSites = true;
bool isLoadingSummary = false;
List<Map<String, dynamic>> previousTransactions = [];
bool isLoadingTransactions = false;
DateTime? startDate;
DateTime? endDate;
@override
void initState() {
super.initState();
_loadSites();
}
Future<void> _loadSites() async {
final siteList = await DatabaseHelper.instance.getSites();
setState(() {
sites = [
{'id': -1, 'name': 'All Sites'},
...siteList
];
isLoadingSites = false;
if (sites.isNotEmpty) {
selectedSiteId = sites.first['id'];
_loadSummaryForSite(selectedSiteId!);
}
});
}
Future<void> _loadSummaryForSite(int siteId) async {
setState(() {
isLoadingSummary = true;
isLoadingTransactions = true;
summary = null;
previousTransactions = [];
});
late final Map<String, dynamic> data;
late final List<Map<String, dynamic>> transactions;
if (siteId == -1) {
data = await DatabaseHelper.instance
.getMonthlyTransactionSummaryAllSites(startDate, endDate);
transactions = await DatabaseHelper.instance
.getAllTransactionsFiltered(startDate, endDate);
} else {
data = await DatabaseHelper.instance
.getFullTransactionSummaryBySite(siteId, startDate, endDate);
transactions = await DatabaseHelper.instance
.getTransactionsBySiteFiltered(siteId, startDate, endDate);
}
setState(() {
summary = data;
previousTransactions = transactions;
isLoadingSummary = false;
isLoadingTransactions = false;
});
}
@override
Widget build(BuildContext context) {
if (isLoadingSites) {
return const Center(child: CircularProgressIndicator());
}
return Scaffold(
backgroundColor: const Color(0xFFF1F8E9),
appBar: AppBar(
backgroundColor: Colors.teal,
title: const Text('Transaction Report'),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("Select Site",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
DropdownButtonFormField<int>(
value: selectedSiteId,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
isExpanded: true,
items: sites.map((site) {
return DropdownMenuItem<int>(
value: site['id'],
child: Text(site['name']),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() {
selectedSiteId = value;
});
_loadSummaryForSite(value);
}
},
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: ElevatedButton.icon(
icon: const Icon(Icons.date_range),
label: Text(
startDate == null || endDate == null
? 'Select Date Range'
: '${DateFormat('dd MMM').format(startDate!)} - ${DateFormat('dd MMM').format(endDate!)}',
),
onPressed: () async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2000),
lastDate: DateTime.now(),
initialDateRange: startDate != null && endDate != null
? DateTimeRange(start: startDate!, end: endDate!)
: null,
);
if (picked != null) {
setState(() {
startDate = picked.start;
endDate = picked.end;
});
_loadSummaryForSite(selectedSiteId!);
}
},
),
),
const SizedBox(width: 8),
if (startDate != null || endDate != null)
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
startDate = null;
endDate = null;
});
_loadSummaryForSite(selectedSiteId!);
},
),
],
),
const SizedBox(height: 24),
if (isLoadingSummary)
const Center(child: CircularProgressIndicator())
else if (summary == null)
const Center(child: Text("No data available."))
else
Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Site: ${sites.firstWhere((s) => s['id'] == selectedSiteId, orElse: () => {
'name': 'Unknown'
})['name']}",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.black87),
),
const SizedBox(height: 12),
_buildRow("Total Income:", summary!['totalIncome'],
color: Colors.green),
_buildRow("Total Expense:", summary!['totalExpense'],
color: Colors.red),
const Divider(),
_buildRow("Net Total:", summary!['netTotal'],
color: Colors.blue),
],
),
),
),
const SizedBox(height: 16),
if (selectedSiteId != null)
Expanded(
child: isLoadingTransactions
? const Center(child: CircularProgressIndicator())
: previousTransactions.isEmpty
? const Center(child: Text("No previous transactions found."))
: ListView.builder(
itemCount: previousTransactions.length,
itemBuilder: (context, index) {
final tx = previousTransactions[index];
final isIncome = tx['type'] == 'income';
final sign = isIncome ? '+' : '-';
final amount = tx['amount'];
return ListTile(
title: Text(
"${tx['type'].toString().toUpperCase()} $sign ₹$amount",
style:
const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Date: ${DateFormat('yyyy-MM-dd').format(DateTime.parse(tx['date']))}',
style: const TextStyle(
fontSize: 14, color: Colors.grey),
),
if (tx['note'] != null &&
tx['note'].toString().trim().isNotEmpty)
Text(
'Note: ${tx['note']}',
style: const TextStyle(
fontSize: 14, color: Colors.black87),
),
Text("Pond: ${tx['pond_name'] ?? 'N/A'}"),
],
),
);
},
),
),
],
),
),
),
);
}
Widget _buildRow(String label, dynamic value, {Color color = Colors.black}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(fontSize: 16)),
Text(
value is double ? value.toStringAsFixed(2) : value.toString(),
style: TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, color: color),
),
],
),
);
}
}
### Key Changes and Explanations
1. **Removed `FutureBuilder`**:
- The original `FutureBuilder` was replaced with a direct check on `isLoadingTransactions` and `previousTransactions`.
- Now, if `isLoadingTransactions` is `true`, it shows a loading indicator.
- If `previousTransactions` is empty, it shows a "No previous transactions found" message.
- Otherwise, it uses `ListView.builder` to display the transactions. This is more efficient as it reuses the data already fetched in `_loadSummaryForSite`.
2. **Handled Loading and Empty States**:
- Used `isLoadingTransactions` to manage the loading state, which is already set in `_loadSummaryForSite`.
- This ensures a consistent user experience without redundant database calls.
3. **Efficiency Improvements**:
- By using the state variable `previousTransactions`, we avoid calling the database multiple times. The data is fetched once when the site or date range changes, and the UI updates accordingly.
4. **No Changes to Other Parts**:
- The rest of the code (e.g., site loading, summary display, date range selection) remains unchanged as it was already functional.
### Additional Suggestions
- **Error Handling**: Consider adding error handling in `_loadSummaryForSite` and `_loadSites` to handle potential database errors (e.g., using `try-catch` and displaying an error message in the UI).
- **Site Name in Transactions**: If "All Sites" is selected, it might be helpful to display the site name for each transaction in the list. You could modify the `DatabaseHelper` methods (e.g., `getAllTransactionsFiltered`) to include a `site_name` field in the transaction maps. Then, add a line like `Text("Site: ${tx['site_name'] ?? 'N/A'}")` in the `ListTile` subtitle.
- **Date Range Default**: If no date range is set, ensure your `DatabaseHelper` methods handle `null` values appropriately (e.g., return all-time data).
- **Performance**: Using `ListView.builder` is already a good choice for potentially large lists, as it builds items lazily.
This corrected code should work more reliably and efficiently. If you have any specific questions or need further modifications, let me know!