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

2,058

Solution 1

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);

Solution 2

a bit shorter and without a check

string.characters.take(30)

enter image description here

Solution 3

Try this

return string.substring(0, string.length < 30 ? string.length : 30);

Solution 4

import 'dart:math';
string.substring(0, min(30, string.length));

enter image description here

In the above picture, you can see that 2 variables below30 and above30

substring(int start, [int? end]);

when we use like this below30.substring(0,30) we get RangeError (end): Invalid value: Not in inclusive range 0..15: 30 error.Becasue below30 length is 15.above30 will give proper result because it have 32 character.

so overcoming this problem You can use like this:

string.substring(0, min(30, string.length));

min(num a, num b)=> Returns the lesser of two numbers. num (abstract class) may double or int.so here we didn't get any error invalid range.

enter image description here

For easy use you can use below30.characters.take(30) no more complexity. @@atreeon.

for bulk data manipulation substring method will much faster than takemethod

Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms

Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms
Share:
2,058
Tobias H.
Author by

Tobias H.

Updated on December 25, 2022

Comments

  • Tobias H.
    Tobias H. over 1 year

    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?

    • Ashok
      Ashok over 3 years
      What's the error you're getting?
    • Sophie-Timezonedesign
      Sophie-Timezonedesign over 3 years
      Can you show me current code?