How to make a custom Calender in Flutter? - flutter

So this is what my calender is supposed to look like;
I'm thinking of making a listView of days, but how do I make it linked to an actual calender so I get the correct days/dates ?

Create the current week from any date using weekday something like this:
void main() {
final any = DateTime.now().add(Duration(days: 2));
final dateOnly = DateTime(any.year, any.month, any.day);
final week = [
for (var i = 1; i <= 7; i++)
dateOnly.subtract(Duration(days: dateOnly.weekday - i))
];
}

Related

How to split a list into sublists using flutter?

I'm new with flutter.
I have data in txt file I retrieve it, then, I convert it into list and finally I split this list into sublists. Every sublist contains 19 values.
It's okey for this part. But now, the problem is that in the end of file we could have less than 19 values. So my question is how to add this values to another sublist also.
Actually, those sublists contains hexadecimals values, I was thinking about filling the last sublist with zeros until we have 19 values.But, I don't know how to do this.
Or, if you have any other solution to fix this issue?
this is my code:
static Future<List> localPath() async {
File textasset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
final text = await textasset.readAsString();
final bytes =
text.split(',').map((s) => s.trim()).map((s) => int.parse(s)).toList();
final chunks = [];
//final list4 = [];
int chunkSize = 19;
for (int i = 0; i < 40; i += chunkSize) {
chunks.add(bytes.sublist(
i, i + chunkSize > bytes.length ? bytes.length : i + chunkSize));
}
return chunks;
}
Thanks in advance for your help
import 'package:collection/collection.dart'; // add to your pubspec
final newList = originalList.slices(19).toList();
Done. Read the documentation for details.
Edit: After reading your comment, I came up with this:
import 'dart:math';
import 'package:collection/collection.dart';
void main(List<String> arguments) {
final random = Random();
const chunkSize = 7;
final source = List.generate(100, (index) => random.nextInt(100) + 1);
List<int> padTo(List<int> input, int count) {
return [...input, ...List.filled(count - input.length, 0)];
}
List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
final items = source.slices(chunkSize).map(padToChunksize).toList();
print(items);
}
which demonstrates how to pad each short list with more 0's.

How to does constructors in provider works?

class Brain with ChangeNotifier {
List<List<IconData>> icon = [];
Brain() {
for (int i = 0; i < 10; i++) {
List<IconData> temp = [];
for (int j = 0; j < 10; j++) {
temp.add(Icons.square_outlined);
}
icon.add(temp);
}
[...]
}
}
After some testing it seems like provider is calling it's constructor every widget state, but my icon list doesn't reset after changing some of the icons. How is it possible?
Well you need to use notifyListeners(); when you need to refresh your Ui, use it at the end of your Brain constructor after your process finished and see the result
Brain() {
...
notifyListeners();
}
Its better to use a function outside the constructor and use that, the constructor will create once when you provide the provider,

Generate 4 random numbers that add to a certain value in Dart

I want to make 4 numbers that add up to a certain number that is predefined.
For instance, I want four random numbers when added gives me 243.
Any type of way works as long as it works :)
this is more a math problem than a programming problem.
Maybe you can do something like this, if 0 is allowed.
var random = new Random();
final predefindedNumber = 243;
var rest = predefindedNumber;
final firstValue = random.nextInt(predefindedNumber);
rest -= firstValue;
final secondValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= secondValue;
final thirdValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= thirdValue;
final fourthValue = rest;
print("$fourthValue $secondValue $thirdValue $fourthValue");
With this implementation it´s possible to get somthing like this 243 0 0 0
This works:
import 'dart:math';
void main() {
int numberOfRandNb = 4;
List randomNumbers = [];
int predefinedNumber = 243;
for(int i = 0; i < numberOfRandNb - 1; i++) {
int randNb = Random().nextInt(predefinedNumber);
randomNumbers.add(randNb);
predefinedNumber -= randNb;
}
randomNumbers.add(predefinedNumber);
print(randomNumbers.join(' '));
}

How to generate random numbers without repetition in Flutter

I need to generate random numbers to use them as index and i need the generated number to be within a range and cannot be repeated. Is there a predefined function in Flutter to do that or am i going to create my own function?
you can use the Random class and then use a Set because unlike List you don't need to do any extra checking for duplication as Set itself won't allow any duplicated element.
for example:
Set<int> setOfInts = Set();
setOfInts.add(Random().nextInt(max));
I think you could simply create a simple shuffled list of index and use removeLast() on it each time you need a new value.
var randomPicker = List<int>.generate(n, (i) => i + 1)..shuffle();
...
int random1 = randomPicker.removeLast();
int random2 = randomPicker.removeLast();
assert(random1 != random2);
Where n is your maximum index.
Use random from math library:
import 'dart:math';
Random random = new Random();
int random_number = random.nextInt(100); // from 0 up to 99
And if you want to change minimum number you can use below trick, it will select from 10 up to 99:
int randomNumber = random.nextInt(90) + 10;
If you need multiple you can add those numbers to list and check them if there is exist with contain, such as:
List<int> numberList=[];
Random random = new Random();
for (var i = 0; i == 10; i++){
int random_number = random.nextInt(100);
if (!numberList.contains(random_number)) {numberList.add(random_number);}
}
I tried using all the codes above but none solved my problem.
I created this and it worked for me:
class Utils {
static final _random = Random();
static final Set<int> _setOfInts = {};
static int randomUnique({required limit}) {
debugPrint("limit: $limit ---> ${_setOfInts.length} ${_setOfInts.toString()}");
int randomInt = _random.nextInt(limit) + 1;
if (_setOfInts.contains(randomInt)) {
return randomUnique(limit: limit);
} else {
_setOfInts.add(randomInt);
return randomInt;
}
}
}

How to calculate ages correctly in GWT?

This is what I did, but it did not take into account the leap years
public static int calculateAge(String yyyyMMddBirthDate){
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
Date birthDateDate = fmt.parse(yyyyMMddBirthDate);
Date nowDate=new Date();
long differenceInMillis=nowDate.getTime()-birthDateDate.getTime();
int days=(int)Math.abs(differenceInMillis/(1000*60*60*24));
int ages=(int)days/365;
System.out.println(days+" days");
return ages;
}
I heard we have to use Joda time to calculate ages, but seem GWT does not support Joda time.
Can we just simply use simple code to calculate ages in GWT rather than using library?
Note: This is GWT question, not Java one. The GWT does not support java.text or Joda.
This should work (even for GWT), at least for births that are after about 1582:
// currentDate and birthDate are in the format yyyyMMdd
final int age = (Integer.valueOf(currentDate) - Integer.valueOf(birthDate)) / 10000;
You've already calculated the age in milliseconds, but you need to convert it to the highly arbitrary Western "years."
Best to use a library like JodaTime or Calendar that have these edge cases programmed in. Luckily people have ported it to GWT.
See: Date time library for gwt
Update: It really depends on what answer you want. Generally, comparing the current year to the birth year would get you the correct answer. So, if you want integer years lived so far:
Date dateBirth = ...;
Date dateNow = new Date();
int yearsOld = dateNow.getYear() - dateBirth.getYear();
To account for the fractional year, you'll need to test for leap days (if you want day precision) or leap seconds (if you want leap second precision). So, again, it depends what result you seek, which you've not said.
Regardless, this has nothing to do with GWT and everything to do with the basics of date/time math. either you'll have to bring it in via a library, or do it yourself. I'd suggest a library, since the calculations are elaborate. Just look inside the BaseCalendar that Java uses.
I ran into this today and here's what I came up with. This models how I would mentally calculate someone's age given a date of birth.
(using com.google.gwt.i18n.shared.DateTimeFormat)
private int getAge(Date birthDate) {
int birthYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(birthDate));
int birthMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(birthDate));
int birthDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(birthDate));
Date today = new Date();
int todayYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(today));
int todayMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(today));
int todayDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(today));
boolean hasHadBirthdayThisYear;
if (todayMonth < birthMonth) {
hasHadBirthdayThisYear = false;
} else if (todayMonth > birthMonth) {
hasHadBirthdayThisYear = true;
} else {
hasHadBirthdayThisYear = birthDayOfMonth <= todayDayOfMonth;
}
int age = todayYear - birthYear;
if (!hasHadBirthdayThisYear) {
age--;
}
return age;
}
import java.util.*;
public class Practice2 {
public static int calculateAge(String yyyyMMddBirthDate) {
// check the input ?
int birthYear = Integer.parseInt(yyyyMMddBirthDate.substring(0,4));
Date nowDate = new Date();
int nowYear = nowDate.getYear() + 1900;
//rough age and check whether need -- below
int roughAge = nowYear - birthYear;
int birthMonth = Integer.parseInt(yyyyMMddBirthDate.substring(5,7));
int birthDay = Integer.parseInt(yyyyMMddBirthDate.substring(8,10));
//1970-01-01T 00:00:00
long now = nowDate.getTime();
long days = now / (3600l * 1000l * 24l);
int daySum = 0;
for( int i = 1970; i < nowYear; i ++ ){
daySum = daySum + yearDays(i);
}
int[] monthDays = {31, 28 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
monthDays[1] = yearDays(nowYear) - 337;
for( int i = 0; i < birthMonth -1; i ++ ){
daySum = daySum + monthDays[i];
}
daySum = daySum + birthDay;
if( daySum > days ){
roughAge--;
}
return roughAge;
}
private static int yearDays(int year) {
if( ( (year%100==0)&&(year%400==0) )
||((year%100!=0)&&(year%4==0))){
return 366;
}
return 365;
}
public static void main(String[] args) {
System.out.println(calculateAge("1990-12-30"));
}
}