I have created a function that generates ExpenseModel
's objects,
While creating an object and setting the date, I used randomly month and day and gave 2022 as a fixed year.
but even though it generates 2021 as well as I have given a random range of 28 but generated 31 also...
Can't figure out where I am doing mistakes...
here is my code
void createexpenses() {
expensies.clear();
for (int x = 1; x <= 50; x ) {
expensies.add(ExpenseModel(
category: categories[Random().nextInt(6)],
amount: Random().nextInt(100),
date: DateTime(2022, Random().nextInt(12), Random().nextInt(28))));
//here i have given fixed year 2022,and day upto 28
}
here is my expense mode
class ExpenseModel
{
String category;
int amount;
DateTime date;
ExpenseModel({required this.category,required this.amount,required this.date});
}
this is my code where I display this expenses...
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),
);
}))
],
),
),
),
);
}
this is code of expense tile
class ExpenseTile extends StatelessWidget {
ExpenseModel data;
ExpenseTile({Key? key,required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(vertical: 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.grey[200],
),
child: ListTile(
title: Text(data.category.toString()),
trailing: Container(
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(20),
),
padding: EdgeInsets.all(10),
child: Text(data.amount.toDouble().toString(),style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),)),
subtitle: Text(DateFormat("dd-MM-yyyy").format(data.date)),
leading: CircleAvatar(child: Text(data.category.substring(0,1)),),
),
);
}
}
CodePudding user response:
Random.nextInt()
Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to [max], exclusive. So in your case your month random have 0-11, and when you enter 0 in month, DateTime class reduces year by 1 and sets month to 12. Same for days, if you get 0, month -1 and day will be last possible day of the month you got.