I am working with a piece of code snippet where I want to generate a random 4-digit code. But unfortunately, I was not able to get the exact output I desired.
I was using this piece of code snippet:
import 'dart:math';
void _generateCode() {
Set<int> setOfInts = {};
setOfInts.add(Random().nextInt(9999));
for (var num in setOfInts) {
if (num.toString().length == 4) {
developer.log('Code: $num');
} else {
developer.log('Code: not a 4 digit code');
}
}
}
@override
void initState() {
super.initState();
_generateCode(); // for testing purposes only
}
The code was mostly generating a 4-digit random code, I thought I could achieve it by including this condition statement,
if (num.toString().length == 4) {
//fortunately, I could get what I want here
}
But the problem is, according to what is printed on the logs (every time I perform a hot reload):
Restarted application in 218ms.
[log] Code: 8308
Restarted application in 221ms.
[log] Code: 6342
Restarted application in 209ms.
[log] Code: 3404
Restarted application in 208ms.
[log] Code: 9468
Restarted application in 246ms.
[log] Code: 1101
Restarted application in 127ms.
[log] Code: 8230
Restarted application in 133ms.
[log] Code: 4104
Restarted application in 220ms.
[log] Code: 6558
Restarted application in 213ms.
[log] Code: not a 4 digit code 👈 here is the part of the issue it produces
Restarted application in 223ms.
[log] Code: 6234
If I removed the else statement from:
if (num.toString().length == 4) {
developer.log('Code: $num');
} else {
developer.log('Code: not a 4 digit code');
}
I wasn't able to get the 4-digit code, I just thought that by using this statement if (num.toString().length == 4)
, it ensures the generation of the 4-digit code, but it didn't.
How can I resolve it to not generate a 3-digit code value?
If we look at the documentation of Random.nextInt
it says:
int nextInt( int max )
Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.
So your Random().nextInt(9999)
can generate any number from 0 to 9998 (note: not 9999). There is no guarantee that the code will be >999, it may just as well be 1, 2, or 3 digits.
Asimple fix is to just start with 1,000 and then add a number from 0 to 8999 to it:
1000 + Random().nextInt(9000)
Note: 9000 as nextInt
will never return the actual max value you pass.