Dart中如何拼接字符串与整数,解决int类型无法赋值给String参数的错误
报错根因
Dart 是强类型语言,+运算符用于字符串拼接时,要求两侧的操作数必须全部为字符串类型,不能直接将整数值和字符串相加,因此会抛出类型不匹配的报错:The argument type 'int' can't be assigned to the parameter type 'String'。
两种可直接解决问题的修改方案
- 采用 Dart 原生的字符串插值语法,这是官方优先推荐的写法,不需要手动做类型转换,只要把需要拼接的整数值放在字符串的
${}占位符中,值就会自动转为字符串完成拼接,原来的两行打印语句修改为:print('Computer is moving to ${i + 1}'); // 双引号包裹的字符串和单引号写法效果完全一致 print("Computer is moving to ${i + 1}"); - 如果坚持保留
+的字符串拼接写法,需要手动给整数计算结果调用toString()方法,将其显式转为字符串后再拼接,原来的两行打印语句修改为:print('Computer is moving to ' + (i + 1).toString()); print("Computer is moving to " + (i + 1).toString());
完成拼接逻辑修改后的完整代码
void getComputerMove() { int move; // 首先判断O方是否存在直接获胜的落子位置 for (int i = 0; i < boardSize; i++) { if (_mBoard[i] != humanPlayer && _mBoard[i] != computerPlayer) { String curr = _mBoard[i]; _mBoard[i] = computerPlayer; if (checkWinner() == 3) { print('Computer is moving to ${i + 1}'); return; } else _mBoard[i] = curr; } } // 判断是否需要阻挡X方的获胜路径 for (int i = 0; i < boardSize; i++) { if (_mBoard[i] != humanPlayer && _mBoard[i] != computerPlayer) { String curr = _mBoard[i]; // 保存棋盘当前位置的原有取值 _mBoard[i] = humanPlayer; if (checkWinner() == 2) { _mBoard[i] = computerPlayer; print("Computer is moving to ${i + 1}"); return; } else _mBoard[i] = curr; } } }
补充:如果后续分析器提示
int move;变量未被使用,可根据业务逻辑移除这行冗余声明。
内容的提问来源于stack exchange,提问作者dbm1211
相关产品推荐
相关产品推荐

