0

I am using this string formatter to have first char toUpperCase in given string (user name), however, if user name is whole in capital letters than it's obviousy gives me nothing. Do you have any idea how to refactor it to make whole string toLowerCase and then make first one capital?

static String upperFirstCase(String str) {
    return "${str[0].toUpperCase()}${str.substring(1)}";
  }
P-J
  • 179
  • 1
  • 14
  • Does this answer your question? [TextAllCaps in Text() widget of Flutter?](https://stackoverflow.com/questions/55654466/textallcaps-in-text-widget-of-flutter) – Dharmesh Mansata Nov 09 '20 at 10:51

2 Answers2

2

try this

String upperFirstCase(String s) =>(s[0].toUpperCase() + s.substring(1).toLowerCase);
ajay
  • 808
  • 9
  • 18
  • 1
    It works if you are sure that passed string is at least 2 characters long. It may be the case, but if not make sure that your code handles too short strings in some way, like @Ashok did in his first approach. – Marcin Wróblewski Nov 09 '20 at 11:25
  • 1
    @MarcinWróblewski you are correct. but he wants to First character to upperCase rest to lower, so it expects more than one character. all the other hand needs validation. – ajay Nov 09 '20 at 11:32
  • 2
    @MarcinWróblewski I just want to format string as Ajay wrote above. So this solution works perfectly for me. Users are forced to type something, so it's impossible to get empty string or null in this case. I just want to format it in this specyfic way ;) – P-J Nov 10 '20 at 13:07
  • It's great to hear it works for you but we need to remember that we're not only people that can come across this thread and above solution might lead to issues for them. This is of course a great solution but it requires _hidden_ prerequisites to work which is what I wanted to stress. – Marcin Wróblewski Nov 12 '20 at 10:21
1

Approach 1

String capitalize(String str) => (str != null && str.length > 1)
    ? str[0].toUpperCase() + str.substring(1)
    : str != null ? str.toUpperCase() : null;

Approach 2

String str= 'sample';      
print(${str[0].toUpperCase()}${str.substring(1).toLowerCase()});
Ashok
  • 3,190
  • 15
  • 31