I want to get first longest string ? How can i do this ?
List<String> list = ['hi', 'hello', 'frozen', 'big mistake', 'cool daddy'];
CodePudding user response:
this is the shortest solution, which will return the longest string:
list.reduce((a, b) {
return a.length > b.length ? a : b;
})
another alternative is:
list.sort((a, b) {
return b.length - a.length;
});
print(list[0]);
CodePudding user response:
Check the below function i have done in my project to get the longest string.
long_string(arr) {
var longest = arr[0];
for (var i = 1; i < arr.length; i ) {
if (arr[i].length > longest.length) {
longest = arr[i];
}
}
return longest;
}
And you can call the function like below to get the longest string
var arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborgsdsdsds"];
print(long_string(arr));
CodePudding user response:
final longestString = list.fold<String>('',
(previousValue, element) =>
element.length > previousValue.length ? element : previousValue)