Flutter应用遇Range Error:索引值不在0..1范围内,求解决方案
解决Flutter中的RangeError: Invalid value not in range 0..1, inclusive: 2错误
嘿,我看到你跟着Flutter教程学习时碰到了这个索引越界的问题,这绝对是新手入门时很常见的小坑,咱们来一步步搞定它!
错误原因分析
先看你的代码:你定义的questions数组只有2个元素,对应的有效索引是0和1。但每次点击按钮时,questionIndex会自增1,当点击第三次时,questionIndex变成了2,这时候再执行questions[questionIndex]就会访问数组里不存在的位置,直接触发RangeError。
具体解决建议
这里给你几个实用的解决方案,你可以根据需求选择:
循环切换问题(推荐)
修改answerQuestion方法,让索引在数组长度范围内循环,这样永远不会越界:void answerQuestion(){ setState(() { // 用取模运算实现循环,索引到最后一个后回到开头 questionIndex = (questionIndex + 1) % questions.length; }); print(questionIndex); }限制索引最大值
如果不想循环,只想停在最后一个问题,可以判断索引是否已经到数组末尾:void answerQuestion(){ setState(() { if(questionIndex < questions.length - 1){ questionIndex += 1; } }); print(questionIndex); }这样点击到最后一个问题后,索引就不会再增加了。
添加越界判断(兜底方案)
在显示文本的时候先检查索引是否有效,避免崩溃:Text( questionIndex < questions.length ? questions[questionIndex] : "没有更多问题啦!" ),
额外的代码优化建议
把questions数组移到State类的成员变量里,不要每次build方法执行时都重新创建,这是更规范的Flutter代码写法:
class MyAppState extends State<MyApp>{ var questionIndex=0; // 把数组定义在这里,只初始化一次 final List<String> questions = [ 'What is your favourite colour', 'What is your favourite animal', ]; void answerQuestion(){ setState(() { questionIndex = (questionIndex + 1) % questions.length; }); print(questionIndex); } @override Widget build(BuildContext context){ return MaterialApp(home: Scaffold( appBar:AppBar(title:Text('my first app'),), body: Column(children:[ Text(questions[questionIndex]), RaisedButton(child: Text("Answer 0"), onPressed:answerQuestion,), RaisedButton(child: Text("Answer 1"), onPressed:answerQuestion,), ],), ),); } }
内容的提问来源于stack exchange,提问作者mutairu
相关产品推荐
相关产品推荐

