You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart递归生成随机数函数触发递归时返回null是什么原因?

问题原因

你的代码核心问题是递归分支没有返回递归调用的结果。Dart语言规定,如果函数的某条执行路径没有显式执行return语句,该路径最终会默认返回null,这就是你触发递归后randomIndex为null的根本原因。

当生成的随机数等于correctIndex进入if分支时,你仅执行了random(0,4)的递归调用,但没有把该调用的返回值向上传递给上层调用方,该if分支走完后没有任何返回操作,因此外层拿到的结果就是null。只有第一次生成的随机数就符合要求进入else分支时,才会正常返回有效值,和你观察到的现象完全匹配。

修复方案

修改递归分支,显式返回递归调用的结果即可,同时建议将correctIndex作为入参传入函数,避免依赖外部变量,代码更健壮:

import 'dart:math';

int random(int min, int max, int correctIndex) {
   var rn = Random();
   int ans = min + rn.nextInt(max - min);
   if (ans == correctIndex) {
     print("Recursive $ans $correctIndex");
     // 此处添加return,将递归生成的结果返回
     return random(min, max, correctIndex);
   } else {
     print("Correct Index $correctIndex 5050 $ans");
     return ans;
   }
}

调用代码对应调整:

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

补充说明

该场景也可以用循环实现,避免极端情况下递归深度过高导致栈溢出,写法参考:

int randomWithoutRecursion(int min, int max, int correctIndex) {
  var rn = Random();
  int ans;
  do {
    ans = min + rn.nextInt(max - min);
  } while(ans == correctIndex);
  return ans;
}

内容的提问来源于stack exchange,提问作者Saad Bashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:15:03