refactor: Make SpendingPieChart stateful to prevent list flicker

This commit is contained in:
2025-05-04 15:05:29 +03:00
parent b9bd506ee6
commit b9bf455631
2 changed files with 47 additions and 43 deletions
+3 -13
View File
@@ -41,7 +41,7 @@ class _ExpensesScreenState extends State<ExpensesScreen> with TickerProviderStat
late Animation<double> _pieChartHeightFactor;
// State variables
int _selectedPieIndex = -1; // Index of the selected pie chart slice
// Removed _selectedPieIndex as it's now managed by SpendingPieChart
int _selectedNavIndex = 0; // Index for bottom navigation bar
bool _isPieChartExpanded = true; // Controls visibility of the pie chart section
bool _isFilterVisible = false; // Controls visibility of the filter chips
@@ -113,16 +113,7 @@ class _ExpensesScreenState extends State<ExpensesScreen> with TickerProviderStat
});
}
// Handles selection of a pie chart slice
void _selectPieCategory(int index) {
setState(() {
// If the same index is selected, deselect (-1), otherwise select the new index
_selectedPieIndex = (_selectedPieIndex == index) ? -1 : index;
});
// Optionally apply filter when pie slice is selected/deselected
// This requires getting the category name from the index, potentially async
// _applyFilterBasedOnPieSelection(index);
}
// Removed _selectPieCategory method as it's now handled internally by SpendingPieChart
// Applies the selected filter to the transaction list
void _applyFilter(String filter) {
@@ -358,8 +349,7 @@ class _ExpensesScreenState extends State<ExpensesScreen> with TickerProviderStat
child: SpendingPieChart(
categories: categories, // Pass categories from stream snapshot
totalExpenses: totalExpenses, // Pass calculated total
selectedPieIndex: _selectedPieIndex,
onSelectPieCategory: _selectPieCategory, // Callback for selection
// Removed selectedPieIndex and onSelectPieCategory props
animation: _pieChartAnimation, // Appearance animation
),
),
+44 -30
View File
@@ -4,22 +4,36 @@ import 'package:intl/intl.dart'; // For number formatting
import '../models/category.dart'; // Keep using the Category model for UI structure
class SpendingPieChart extends StatelessWidget {
// Changed to StatefulWidget to manage its own selection state
class SpendingPieChart extends StatefulWidget {
final List<Category> categories; // Expect List<Category> from database calculation
final double totalExpenses;
final int selectedPieIndex;
final Function(int) onSelectPieCategory; // Callback when a slice is selected/deselected
final Animation<double> animation; // For fade/scale animation
const SpendingPieChart({
Key? key,
required this.categories,
required this.totalExpenses,
required this.selectedPieIndex,
required this.onSelectPieCategory,
required this.animation,
// Removed selectedPieIndex and onSelectPieCategory
}) : super(key: key);
@override
State<SpendingPieChart> createState() => _SpendingPieChartState();
}
class _SpendingPieChartState extends State<SpendingPieChart> {
// State for the selected index is now managed internally
int _selectedPieIndex = -1;
// Handles selection logic internally
void _handlePieTap(int index) {
setState(() {
// If the same index is selected, deselect (-1), otherwise select the new index
_selectedPieIndex = (_selectedPieIndex == index) ? -1 : index;
});
}
@override
Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
@@ -27,11 +41,11 @@ class SpendingPieChart extends StatelessWidget {
final currencyFormatter = NumberFormat.currency(locale: 'en_US', symbol: '\$'); // Or your preferred locale/symbol
// Handle the case where there are no categories to display
if (categories.isEmpty) {
if (widget.categories.isEmpty) {
return AnimatedBuilder( // Still use animation for consistency
animation: animation,
animation: widget.animation,
builder: (context, child) => Opacity(
opacity: animation.value,
opacity: widget.animation.value,
child: Container(
height: 230, // Maintain similar height to the chart version
alignment: Alignment.center,
@@ -48,12 +62,12 @@ class SpendingPieChart extends StatelessWidget {
// Use AnimatedBuilder to apply the fade/scale animation
return AnimatedBuilder(
animation: animation,
animation: widget.animation,
builder: (context, child) {
return Transform.scale(
scale: animation.value, // Apply scale animation
scale: widget.animation.value, // Apply scale animation
child: Opacity(
opacity: animation.value, // Apply fade animation
opacity: widget.animation.value, // Apply fade animation
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8.0), // Reduced vertical padding
height: 230, // Fixed height for the chart and legend area
@@ -76,13 +90,13 @@ class SpendingPieChart extends StatelessWidget {
if (section != null) {
// Tap occurred ON a section
final touchedIndex = section.touchedSectionIndex;
// Toggle selection: if tapped section is already selected, deselect (-1), otherwise select it.
onSelectPieCategory(touchedIndex == selectedPieIndex ? -1 : touchedIndex);
// Use internal handler to update state
_handlePieTap(touchedIndex);
} else {
// Tap occurred OUTSIDE any section
// Deselect if something was selected
if (selectedPieIndex != -1) {
onSelectPieCategory(-1);
if (_selectedPieIndex != -1) {
_handlePieTap(-1); // Pass -1 to deselect
}
}
}
@@ -99,7 +113,7 @@ class SpendingPieChart extends StatelessWidget {
swapAnimationCurve: Curves.easeInOut,
),
// --- Center Text (Displayed when a slice is selected) ---
if (selectedPieIndex != -1)
if (_selectedPieIndex != -1)
_buildCenterText(context, currencyFormatter)
else // Optional: Display total or default text when nothing is selected
_buildDefaultCenterText(context, currencyFormatter),
@@ -113,7 +127,7 @@ class SpendingPieChart extends StatelessWidget {
flex: 4, // Allocate space for the legend
// Use ListView for scrollable legend if many categories
child: ListView.builder(
itemCount: categories.length,
itemCount: widget.categories.length,
padding: const EdgeInsets.only(right: 8), // Padding for legend items
itemBuilder: (context, index) => _buildPieLegendItem(context, index),
),
@@ -131,11 +145,11 @@ class SpendingPieChart extends StatelessWidget {
Widget _buildCenterText(BuildContext context, NumberFormat formatter) {
final theme = Theme.of(context);
// Check if selectedPieIndex is valid before accessing categories
if (selectedPieIndex < 0 || selectedPieIndex >= categories.length) {
if (_selectedPieIndex < 0 || _selectedPieIndex >= widget.categories.length) {
// Return an empty container or default text if index is invalid
return _buildDefaultCenterText(context, formatter);
}
final selectedCategory = categories[selectedPieIndex];
final selectedCategory = widget.categories[_selectedPieIndex];
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
@@ -177,7 +191,7 @@ class SpendingPieChart extends StatelessWidget {
),
const SizedBox(height: 4),
Text(
formatter.format(totalExpenses), // Display total expenses
formatter.format(widget.totalExpenses), // Display total expenses
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: theme.textTheme.bodyLarge?.color // Use default text color
@@ -193,18 +207,18 @@ class SpendingPieChart extends StatelessWidget {
Widget _buildPieLegendItem(BuildContext context, int index) {
final isDark = Theme.of(context).brightness == Brightness.dark;
final theme = Theme.of(context);
final isSelected = index == selectedPieIndex; // Check if this item is selected
final isSelected = index == _selectedPieIndex; // Check if this item is selected using internal state
// Check if index is valid before accessing categories
if (index < 0 || index >= categories.length) {
if (index < 0 || index >= widget.categories.length) {
return const SizedBox.shrink(); // Return empty if index is invalid
}
final category = categories[index];
final category = widget.categories[index];
// Calculate percentage, handle totalExpenses being zero
final percentage = totalExpenses > 0 ? (category.amount / totalExpenses * 100) : 0.0;
final percentage = widget.totalExpenses > 0 ? (category.amount / widget.totalExpenses * 100) : 0.0;
// Use InkWell for tap feedback and GestureDetector for tap logic
return InkWell(
onTap: () => onSelectPieCategory(isSelected ? -1 : index), // Toggle selection on tap
onTap: () => _handlePieTap(index), // Use internal handler on tap
borderRadius: BorderRadius.circular(8), // Match border radius
child: AnimatedContainer(
duration: const Duration(milliseconds: 200), // Animation for selection change
@@ -264,21 +278,21 @@ class SpendingPieChart extends StatelessWidget {
List<PieChartSectionData> _generatePieSections(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return List.generate(categories.length, (i) {
return List.generate(widget.categories.length, (i) {
// Check if index is valid before accessing categories
if (i < 0 || i >= categories.length) {
if (i < 0 || i >= widget.categories.length) {
// This should ideally not happen if List.generate is used correctly,
// but adding a safeguard.
return PieChartSectionData(); // Return an empty section
}
final isTouched = i == selectedPieIndex; // Check if this slice is selected
final isTouched = i == _selectedPieIndex; // Check if this slice is selected using internal state
// Make selected slice slightly larger
final double radius = isTouched ? 65 : 55;
// Make title font slightly larger when selected
final double titleFontSize = isTouched ? 14 : 12;
final category = categories[i];
final category = widget.categories[i];
// Calculate percentage for the title
final percentage = totalExpenses > 0 ? (category.amount / totalExpenses * 100) : 0;
final percentage = widget.totalExpenses > 0 ? (category.amount / widget.totalExpenses * 100) : 0;
return PieChartSectionData(
color: category.colorCode.withOpacity(isDark ? 0.85 : 1.0), // Use category color