'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 1:[1]

Try this

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

Solution 2:[2]

a bit shorter and without a check

string.characters.take(30)

enter image description here

Solution 3:[3]

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

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 lava
Solution 3 lava
Solution 4 Barsum