Dart - How to concatenate a String and my integer

2,993

Solution 1

With string interpolation:

print("Computer is moving to ${i + 1}"); 

Or just call toString():

print("Computer is moving to " + (i + 1).toString()); 

Solution 2

You can simply use .toString which will convert your integer to String :

void main(){
     
    String str1 = 'Welcome to Matrix number ';
    int n = 24;
     
    //concatenate str1 and n
    String result = str1 + n.toString();
     
    print(result);
}

And in your case it's gonna be like this :

print("Computer is moving to " + (i + 1).toString()); 
Share:
2,993
dbm1211
Author by

dbm1211

Updated on December 27, 2022

Comments

  • dbm1211
    dbm1211 over 1 year

    How can I concatenate my String and the int in the lines: print('Computer is moving to ' + (i + 1)); and print("Computer is moving to " + (i + 1));

    I cant figure it out because the error keeps saying "The argument type 'int' can't be assigned to the parameter type 'String'

    void getComputerMove() {
        int move;
    
        // First see if there's a move O can make to win
        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;
          }
        }
    
        // See if there's a move O can make to block X from winning
        for (int i = 0; i < boardSize; i++) {
          if (_mBoard[i] != humanPlayer && _mBoard[i] != computerPlayer) {
            String curr = _mBoard[i]; // Save the current number
            _mBoard[i] = humanPlayer;
            if (checkWinner() == 2) {
              _mBoard[i] = computerPlayer;
              print("Computer is moving to " + (i + 1));
              return;
            } else
              _mBoard[i] = curr;
          }
        }
      }
    
  • Priyshrm
    Priyshrm over 2 years
    How to append null if n is null? Basically, what is the best way to achieve what Java does. print("hell"+x); should print hellnull if x is null, for any type of x.
  • ParSa
    ParSa over 2 years
    @Priyshrm if you want to print null , you can check the statement and if it was null , print the null : print(x == null ? "null" : x)