I've decided to write a program that runs into an infinite execution of the method where I was testing (to automate the testing process).
Here's the code snippet I was working with to achieve what Ken White and Frank van Puffelen recommend.
import 'dart:math';
import 'package:flutter/material.dart';
import 'dart:developer' as developer;
class FourDigitCodeGenerator extends StatefulWidget {
const FourDigitCodeGenerator({super.key});
@override
State<FourDigitCodeGenerator> createState() => _FourDigitCodeGeneratorState();
}
class _FourDigitCodeGeneratorState extends State<FourDigitCodeGenerator> {
String? _code;
void _generateCode() { // version 1
Set<int> setOfInts = {};
var scopedCode = Random().nextInt(9999);
setOfInts.add(scopedCode);
for (var num in setOfInts) {
if (num < 999) return;
if (num.toString().length == 4) {
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_code = num.toString();
developer.log('Code: $num');
});
});
}
} else {
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_code = num.toString();
developer.log('Code: not a 4 digit code');
});
});
}
}
}
}
void _generateCode2() { // version 2
Set<int> setOfInts = {};
var scopedCode = 1000 + Random().nextInt(9000);
setOfInts.add(scopedCode);
for (var num in setOfInts) {
// if (num < 999) return;
if (num.toString().length == 4) {
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_code = num.toString();
developer.log('Code: $num');
});
});
}
} else {
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_code = num.toString();
developer.log('Code: not a 4 digit code');
});
});
}
}
}
}
@override
Widget build(BuildContext context) {
return Builder(builder: (context) {
_generateCode2();
return Scaffold(
appBar: AppBar(
title: Text('Device ID'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Code: ${_code ?? 'Nothing to show'}'),
],
),
),
);
});
}
}
Here's the output it provides using version 2 method:
Note: I can't embed a GIF file yet, so it is converted into a link instead (by default).
With the solution provided by Ken White (method version 1)
and Frank van Puffelen (method version 2)
produces the same outcomes.
So a big thanks to them!
I hope my answer would help the other future readers as well!