I am creating a list view that shows all expenses, and here I want to do something interesting that this listview should be shown with a header inside it..
like, there are 10 entries of same month, header should b shown with month name as a separator...
I have attached an image to make it very clear,
here is my simple code
Is it logically or have some Widget for it
class ExpenseModel
{
String category;
int amount;
DateTime date;
ExpenseModel({required this.category,required this.amount,required this.date});
}
void createexpenses() {
expensies.clear();
int m,d,y;
for (int x = 1; x <= 50; x ) {
expensies.add(ExpenseModel(
category: categories[Random().nextInt(6)],
amount: Random().nextInt(100),
date:DateTime(2022, Random().nextInt(6) 1, Random().nextInt(28) 1)));
//here i want to give random date;
}
totalexpense=expensies.fold(0, (previousValue, element) {
return previousValue element.amount;
});
expensies.sort((a,b)=>a.date.compareTo(b.date));
}
Widget build(BuildContext context) {
createexpenses(); //creating 50 objects of ExpenseModel
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
children: [
StatusWidget(amount:totalexpense),
SizedBox(
height: 10,
),
Expanded(
child: ListView.builder(
itemCount: expensies.length,
itemBuilder: (context, index) {
final data = expensies[index];
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: ExpenseTile(data: data),
);
}))
],
),
),
),
);
}
CodePudding user response:
Try this:
ListView.builder(
itemCount: expensies.length,
itemBuilder: (context, index) {
final data = expensies[index];
String previousDate = index > 0
? DateFormat('MMM yyyy').format(expensies[index - 1].date)
: '';
String date = DateFormat('MMM yyyy').format(data.date);
return Column(
children: [
date != previousDate
? Container(
alignment: Alignment.center,
child: Text(date),
)
: SizedBox(),
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: ExpenseTile(data: data),
),
],
);
}),