skip to Main Content

I want to get first longest string ? How can i do this ?

List<String> list = ['hi', 'hello', 'frozen', 'big mistake', 'cool daddy'];

4

Answers


  1. final longestString = list.fold<String>('', 
      (previousValue, element) => 
        element.length > previousValue.length ? element : previousValue)
    
    Login or Signup to reply.
  2. 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));
    
    Login or Signup to reply.
  3. 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]);
    
    Login or Signup to reply.
  4. The solution posted by Sparko Sol could also be used in an extension on List<String> to make it easier to reuse this method anywhere in the codebase. Such an extension could look something like

    extension Longest on List<String> {
      /// Returns the longest element in a [List<String>]
      String longest() {
        return reduce((a, b) {
          return a.length > b.length ? a : b;
        });
      }
    }
    

    Then, to use this extension, you could simply write something like

    String longestString = list.longest();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search