Dart tips for better programming about passing arguments between class - flutter

Can anyone give me some guidance or tips about better dart programming for my code below?
Can it be more simpler?
I think it's not good enough, and I also have a question about 'if statement' construction which i added inside the code.
void main() {
int month = 12;
int day = 1;
int year = 2022;
int newDay;
int newMonth;
int newYear;
Calculate calculate = Calculate(day,month,year);
newDay = calculate.newDay;
newMonth = calculate.newMonth;
newYear = calculate.newYear;
if (newMonth > 7) {
newYear +=1;}
print('New date is : $newDay / $newMonth / $newYear');
}
class Calculate{
int month;
int day;
int year;
Calculate(this.day, this.month, this.year);
get newDay => day + 7;
get newMonth => month + 1;
get newYear => year + 1;
//QUESTION.. how to construct below 'if statement' within this class?
//if newMonth > 7 then newYear += 1;
}
I make some changes to remove the classes, but i can't return the value, please help how to fix this :
void main() {
int month = 12;
int day = 1;
int year = 2022;
print(Calculate(day,month,year));
}
Calculate(day,month,year){
int newday = 0;
int newmonth = 0 ;
int newyear = 0;
newday = day + 7;
newmonth = month + 1;
newyear = year + 1;
List<int> result;
if (month > 3) {
return '$newday/$newmonth/$newyear';}
else {return '$newday/$newmonth/$newyear+1';}
}

Not really understand what you want to do, but here is a little example. You can play with it and change your preferences.
void main() {
DateData data = DateData(day: 5, month: 12, year: 2022);
DateData newData = DateData(day: data.day, month: 8, year: 2022)
.calculateYear()
.calculateMonth()
.calculateDay();
print(data.toString());
print(newData.toString());
}
class DateData {
DateData({
required this.day,
required this.month,
required this.year,
});
int day;
int month;
int year;
#override
String toString() => 'DateData(day: $day, month: $month, year: $year)';
DateData calculateYear() {
// Do something with `year` value.
if (month > 7) {
year += 1;
}
return this;
}
DateData calculateDay() {
// Do something with `day` value.
if (day > 31) {
day = 1;
}
return this;
}
DateData calculateMonth() {
// Do something with `month` value.
if (month > 12) {
month = 1;
}
return this;
}
}

You should replace your Calculate class with a function. There is no need for a class here.

Related

Flutter how to use multiple forloops

I am using this code but sometimes it runs the code in wrong order. Is it possible to wait for each for loop to finish before next one starts?
void changeWeek() {
for (int i = 0; i < newactivities.length; i++) {
int year = DateTime.now().year;
DateTime startDate = DateTime(year, 1, 1);
while (startDate.weekday != DateTime.monday) {
startDate = startDate.add(const Duration(days: 1));
}
for (String weekday in newactivities[i].daylistdone) {
int offset = (int.parse(weekday)) + (int.parse(currentweek) - 1) * 7;
DateTime donedate = startDate.add(Duration(days: offset));
oldDatesDone.add(Timestamp.fromDate(donedate));
}
for (String weekday in newactivities[i].daylist) {
int offset =
(int.parse(weekday) - 1) + (int.parse(currentweek) - 1) * 7;
DateTime notdonedate = startDate.add(Duration(days: offset));
oldDatesNotDone.add(Timestamp.fromDate(notdonedate));
}
for (var i in oldDatesDone) {
oldDatesNotDone.remove(i);
}
finaloldDatesDone = newactivities[i].weekdaysdone + oldDatesDone;
finaloldDatesNotDone = newactivities[i].weekdaysnotdone + oldDatesNotDone;
act.add({
'title': newactivities[i].title,
'days': newactivities[i].daylist,
'notificationidnumber': newactivities[i].notificationidnumber,
'daysdone': myData22,
'weekdaysdone': finaloldDatesDone,
'weekdaysnotdone': finaloldDatesNotDone,
'timelist': newactivities[i].timelist,
'time': newactivities[i].time
});
FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
}
Or can I do it in another way to solve the code?
Your Firebase update returns a Future, so it is an asynchronous operation. To preserve order of calls, you need to await the result of this call:
void changeWeek() async {
// ...
await FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
Note that you need do declare the changeWeek() function as async for this to work.

How to get the first, second, third, and fourth week of the month?

I want to get all four weeks (first and last day date) on the current month with Monday as the start of the week.
I can only figure out how to get the current week's first and last date with this code:
var firstDayOfTheWeek = DateTime.now().subtract(Duration(days: DateTime.now().weekday - 1));
var lastDayOfTheWeek = DateTime.now().add(Duration(days: DateTime.daysPerWeek - DateTime.now().weekday));
Thanks in advance!
Below method return next weekday's DateTime what you want from now or specific day.
DateTime getNextWeekDay(int weekDay, {DateTime from}) {
DateTime now = DateTime.now();
if (from != null) {
now = from;
}
int remainDays = weekDay - now.weekday + 7;
return now.add(Duration(days: remainDays));
}
The weekday parameter can be came like below DateTime const value or just int value.
class DateTime {
...
static const int monday = 1;
static const int tuesday = 2;
static const int wednesday = 3;
static const int thursday = 4;
static const int friday = 5;
static const int saturday = 6;
static const int sunday = 7;
...
}
If you want to get next Monday from now, call like below.
DateTime nextMonday = getNextWeekDay(DateTime.monday);
If you want to get next next Monday from now, call like below.
Or you just add 7 days to 'nextMonday' variable.
DateTime nextMonday = getNextWeekDay(DateTime.monday);
DateTime nextNextMonday = getNextWeekDay(DateTime.monday, from: nextMonday);
or
DateTime nextNextMonday = nextMonday.add(Duration(days: 7));

How to have duration.years and duration.month in flutter?

Hello currently I display a timer with two digit ( DD HH mm SS)
I would like to display a new timer like ( YY MM DD HH)
Here is my current code
String _formatDuration_conso(Duration duration) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
String twoDigitHours = twoDigits(duration.inHours.remainder(24));
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inDays)} $twoDigitHours $twoDigitMinutes $twoDigitSeconds";
}
Thank you
Convert days into years
int inYears(int days) {
if (days < 1) return 0;
return days~/365;
}
and then
String _formatDuration_conso(Duration duration) {
//..
return "${twoDigits(inYears(duration.inDays))} ${twoDigits(duration.inDays)} $twoDigitHours $twoDigitMinutes $twoDigitSeconds";
}

Get current Week of the Month as a Number

How do I get the current week of the month as a number in Dart? I need to create some sort of calender with a week view where it says something like "2. Week of January"
You can use DateTime().now() to get the current time and date of the system or today's date also. Here is the code snippet below:
// Current date and time of system
String date = DateTime.now().toString();
// This will generate the time and date for first day of month
String firstDay = date.substring(0, 8) + '01' + date.substring(10);
// week day for the first day of the month
int weekDay = DateTime.parse(firstDay).weekday;
DateTime testDate = DateTime.now();
int weekOfMonth;
// If your calender starts from Monday
weekDay--;
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
weekDay++;
// If your calender starts from sunday
if (weekDay == 7) {
weekDay = 0;
}
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
Alternatively, if are looking for a complete implementation of the calender month UI then click here
My Answer is impaired from #dblank answer
extension DateTimeExtension on DateTime {
int get weekOfMonth {
var date = this;
final firstDayOfTheMonth = DateTime(date.year, date.month, 1);
int sum = firstDayOfTheMonth.weekday - 1 + date.day;
if (sum % 7 == 0) {
return sum ~/ 7;
} else {
return sum ~/ 7 + 1;
}
}
}
Then use it like this:
var wom = DateTime.now().weekOfMonth;
extension DateTimeExtension on DateTime {
int get weekOfMonth {
var wom = 0;
var date = this;
while (date.month == month) {
wom++;
date = date.subtract(const Duration(days: 7));
}
return wom;
}
}
Then use it like this:
var wom = DateTime.now().weekOfMonth;

Dart: How to find number of days between two dates excluding Weekend or Predicate

I need to calculate number of days between two dates in Dart.
There is built in function for that.
leaveEndDate.difference(leaveStartDate).inDays
But I do not want weekends to be included.
Is there any way I can traverse between these 2 Dates or I can just exclude weekends.
I think you have no other choice than looping through all the days to check if this is a weekend day or not :
void main() {
DateTime date1 = DateTime(2019, 12, 01);
DateTime date2 = DateTime(2019, 12, 31);
print(getDifferenceWithoutWeekends(date1, date2));
}
int getDifferenceWithoutWeekends(DateTime startDate, DateTime endDate) {
int nbDays = 0;
DateTime currentDay = startDate;
while (currentDay.isBefore(endDate)) {
currentDay = currentDay.add(Duration(days: 1));
if (currentDay.weekday != DateTime.saturday && currentDay.weekday != DateTime.sunday) {
nbDays += 1;
}
}
return nbDays;
}
Result :
22
EDIT :
Another solution, not sure it is faster but can be useful if you need to identify the dates (you could return list<DateTime> instead of List<int> to see which day is a weekend day).
Here I build each days between the 2 dates and return 1 if this is not a weekend day, then sum the list :
void main() {
DateTime startDate = DateTime(2019, 12, 01);
DateTime endDate = DateTime(2019, 12, 31);
int nbDays = endDate.difference(startDate).inDays + 1;
List<int> days = List.generate(nbDays, (index) {
int weekDay = DateTime(startDate.year, startDate.month, startDate.day + (index)).weekday;
if (weekDay != DateTime.saturday && weekDay != DateTime.sunday) {
return 1;
}
return 0;
});
print(days.reduce((a, b) => a + b));
}
I have also prepared a function which will traverse to all dates between two dates in Dart and will calculate number of days inBetween.
int calculateDaysBetween(DateTime mStartDate, DateTime mEndDate) {
int leaveDays = mEndDate.difference(mStartDate).inDays + 1;
int leaveBalance = 0;
var mTempDateTime =
DateTime(mStartDate.year, mStartDate.month, mStartDate.day);
for (int i = 0; i < leaveDays; i++) {
mTempDateTime = DateTime(
mTempDateTime.year, mTempDateTime.month, mTempDateTime.day + 1);
if (mTempDateTime.weekday == DateTime.friday ||
mTempDateTime.weekday == DateTime.saturday) {
print('is weekend');
} else {
leaveBalance++;
}
print(mTempDateTime);
}
// Total number of days between two dates excluding weekends.
return leaveBalance;
}
Improve #Developine Answer and make it more reusable , I make 2 function.
1.Calculate Total Days Of Month
2.Calculate TotalWeekDayOfMonth
Get Total Days Of Month
int totalDaysOfMonth(int month, int year) {
final result = (month < 12) ? DateTime(year, month + 1, 0) : DateTime(year + 1, 1, 0);
return result.day;
}
Get Total WeekDay Of Month
int totalWeekDayOfMonth(int year, int month, {int day = 1}) {
int totalDayOfMonth = totalDaysOfMonth(year, month);
int result = 0;
DateTime tempDateTime = DateTime(year, month, day);
for (int i = day; i <= totalDayOfMonth; i++) {
tempDateTime = DateTime(tempDateTime.year, tempDateTime.month, i);
if (tempDateTime.weekday == DateTime.saturday || tempDateTime.weekday == DateTime.sunday) {
print('is weekend');
} else {
result++;
}
}
return result;
}
How To Use It
void main(){
final resultWithoutDay = totalWeekDayOfMonth(2019,12);
final resultWithDay = totalWeekDayOfMonth(2019,12,day: 16);
print("Without Day $resultWithoutDay"); // 22
print("With Day $resultWithDay"); // 12
}