首页 > 解决方案 > Dart - 返回 null 的递归函数

问题描述

我正在尝试创建一个简单的递归函数,它生成一个介于 0 和 4 之间的随机数,并且这个生成的数字不应该等于“correctIndex”。

random(min, max) {
   var rn = new Random();
   int ans = 0;
   ans = (min + rn.nextInt(max - min));
   if (ans == correctIndex) {
     print("Recursive $ans $correctIndex");
     random(0, 4);
   } else {
     print("Correct Index $correctIndex 5050 $ans");
     return ans;
   }
 }

我将上述函数调用如下:

setState(() {
  randomIndex = random(0, 4);
});
print("output value of $randomIndex");

递归部分不被称为“randomIndex”的时间有一个值。但是无论何时调用递归部分,即使函数返回一个值,randomIndex 的值也为 null。以下是调用递归时调试控制台的输出

I/flutter ( 5071): Recursive 2 2
I/flutter ( 5071): Correct Index 2 5050 3
I/flutter ( 5071): output value of null

如果没有调用递归,以下是输出:

I/flutter ( 5071): Correct Index 2 5050 1
I/flutter ( 5071): output value of 1

有人可以指导我做错什么。先感谢您。

标签: flutterdartrecursion

解决方案


这段代码相当于:

random(min, max) {
   var rn = new Random();
   int ans = 0;
   ans = (min + rn.nextInt(max - min));
   if (ans == correctIndex) {
     print("Recursive $ans $correctIndex");
     random(0, 4);
   } else {
     print("Correct Index $correctIndex 5050 $ans");
     return ans;
   }
   return null; // <-- NOTE! dart (flutter) will auto do this.
 }

因此,当if为真时,您最终将返回 null!

所以也许你想random(0, 4);成为return random(0,4)


推荐阅读