Reputation: 505
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?
Upvotes: 3
Views: 3782
Reputation: 7451
import 'dart:math';
string.substring(0, min(30, string.length));
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
.
For easy use you can use below30.characters.take(30)
no more complexity.
@@atreeon.
for bulk data manipulation substring
method will much faster than take
method
Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms
Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms
Upvotes: 6
Reputation: 2391
Try this
return string.substring(0, string.length < 30 ? string.length : 30);
Upvotes: 2
Reputation: 607
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);
Upvotes: 3