dart

How to get first character from words in flutter dart?


Let's say we have a name set to "Ben Bright". I want to output to the user "BB", with the first characters of each word. I tried with the split() method, but I failed to do it with dart.

String getInitials(bank_account_name) {
  List<String> names = bank_account_name.split(" ");
  String initials;
  for (var i = 0; i < names.length; i++) {
    initials = '${names[i]}';
  }
  return initials;
}

Solution

  • Just a slight modification since you only need the first letters

    String getInitials(bank_account_name) {
      List<String> names = bank_account_name.split(" ");
      String initials = "";
      int numWords = 2;
      
      if(numWords < names.length) {
        numWords = names.length;
      }
      for(var i = 0; i < numWords; i++){
        initials += '${names[i][0]}';
      }
      return initials;
    }
    

    Edit: