Flutter访问数组索引拼接字符串出现RangeError错误如何解决?
问题原因
- 运算符优先级错误:
+运算符优先级高于三目运算符?:,你原代码没有给三目运算加括号,实际执行逻辑和预期的「分别取两个字符再拼接」完全不符,会导致即使输入不符合要求也会尝试访问字符串索引。 - 索引校验不完整:你需要取第二个输入的1号索引(对应第二位字符),仅判断长度>0是不够的,需要长度≥2才不会越界。
修复方案
推荐将按钮点击逻辑抽离出来单独处理,补全校验逻辑,还可以增加输入不符合要求的用户提示,修改后的代码如下:
children: [ TextField( controller: firstTextEditingController, decoration: InputDecoration( hintText: 'Insert first input', filled: true, contentPadding: EdgeInsets.all(20), ), style: TextStyle(color: Colors.black), ), const SizedBox( height: 20, ), TextField( controller: secondTextEditingController, decoration: InputDecoration( hintText: 'Insert second input', filled: true, contentPadding: EdgeInsets.all(20), ), style: TextStyle(color: Colors.black), ), const SizedBox( height: 55, ), ElevatedButton( style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 50, vertical: 18)), onPressed: () { String firstInput = firstTextEditingController.text; String secondInput = secondTextEditingController.text; String result = ''; // 校验第一个输入长度,符合要求再取0号索引 if (firstInput.length >= 1) { result += firstInput[0]; } // 校验第二个输入长度≥2,符合要求再取1号索引 if (secondInput.length >= 2) { result += secondInput[1]; } if (result.length == 2) { // 输入符合要求才跳转页面 Navigator.of(context).push(MaterialPageRoute( builder: (context) => NextPage(result: result), fullscreenDialog: true, )); } else { // 输入不符合要求时给用户提示 ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('请保证第一个输入至少1位,第二个输入至少2位')) ); } }, child: const Text('Calculate'), ) ],
如果你不想抽离逻辑,也可以通过加括号修正优先级+补全长度校验直接修改原代码:
result: (firstTextEditingController.text.length >=1 ? firstTextEditingController.text[0] : '') + (secondTextEditingController.text.length >=2 ? secondTextEditingController.text[1] : '')
内容的提问来源于stack exchange,提问作者bilbo_bo
相关产品推荐
相关产品推荐

