Search code examples
stringfluttersubstring

How to substring 0 to 30, but only if there is over 30 characters


I have a little problem, I want to substring a String, to max 30 characters, but when I do string.substring(0, 30), it works fine if the string is 30+ characters, but if not, it comes with an error.

Does anyone know how to fix that?


Solution

  • You should be getting "RangeError: Value not in range: 30" error.

    Try to add a length control before that.

    if (string.length < 30)
    
      return string;
    
    else
    
      return string.substring(0, 30);
    

    Let's shorten the code above:

    String resultText = (string.length < 30) ? string : string.substring(0, 30);