部分For循环无报错未执行、其余循环正常运行问题求助
问题根因
- 所有for循环的遍历条件写反了:遍历正向下标从0开始的集合,应该用
index < 集合长度作为循环继续的条件,你写的index >= 集合长度只有当集合为空时才会进入一次,正常有数据的场景下条件直接不成立,所以循环不会执行。 - 你观察到的第二个循环"正常运行"是假象:因为第一个循环完全没执行,
usernameHashes始终是空列表,长度为0,此时0 >= 0条件成立进入循环,但是此时访问usernameHashes[index]会直接触发数组越界错误,你没看到报错大概率是isolate的异常没有被上层捕获。
其他逻辑错误
- 授权判断逻辑错误:当前三目表达式每次循环都会覆盖
authorized的值,即使前面已经匹配到合法凭证,只要后面有不匹配的记录,最终authorized会被错误覆盖为false。正确写法是匹配到合法凭证后直接赋值true并跳出循环,不要对false的情况做覆盖。 - 代码逻辑冗余:三个循环实现的是完全相同的功能,不需要拆分,只要保留一个循环遍历处理即可。
修正后代码示例
Future<bool> offlineAuthenticationThread(List<Tuple2<String, String>> storedCredentials) async { print('Isolate running'); final DBCrypt hashing = DBCrypt(); bool authorized = false; // 取出输入的待校验账号密码 String inputUserName = storedCredentials[0].item1; String inputPassword = storedCredentials[0].item2; // 移除第一个元素后遍历剩余的存储凭证 storedCredentials.removeAt(0); for (var index = 0; index < storedCredentials.length; index++) { final storedNameHash = storedCredentials[index].item1; final storedPwdHash = storedCredentials[index].item2; if (hashing.checkpw(inputUserName, storedNameHash) && hashing.checkpw(inputPassword, storedPwdHash)) { authorized = true; // 匹配到直接退出循环,不需要继续遍历 break; } } return authorized; }
内容的提问来源于stack exchange,提问作者RobbB
相关产品推荐
相关产品推荐

