How to capitalize the first letter of a string in dart?
StringFlutterDartLetterCapitalizeString Problem Overview
How do I capitalize the first character of a string, while not changing the case of any of the other letters?
For example, "this is a string" should give "This is a string".
String Solutions
Solution 1 - String
Since dart version 2.6, dart supports extensions:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
So you can just call your extension like this:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
Solution 2 - String
Copy this somewhere:
extension StringCasingExtension on String {
String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
String toTitleCase() => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized()).join(' ');
}
Usage:
// import StringCasingExtension
final helloWorld = 'hello world'.toCapitalized(); // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase(); // 'Hello World'
Solution 3 - String
Substring parsing in the other answers do not account for locale variances.
The toBeginningOfSentenceCase() function in the intl/intl.dart
package handles basic sentence-casing and the dotted "i" in Turkish and Azeri.
import 'package:intl/intl.dart' show toBeginningOfSentenceCase;
print(toBeginningOfSentenceCase('this is a string'));
Solution 4 - String
void main() {
print(capitalize("this is a string"));
// displays "This is a string"
}
String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
See this snippet running on DartPad : https://dartpad.dartlang.org/c8ffb8995abe259e9643
Solution 5 - String
There is a utils package that covers this function. It has some more nice methods for operation on strings.
Install it with :
dependencies:
basic_utils: ^1.2.0
Usage :
String capitalized = StringUtils.capitalize("helloworld");
Github:
Solution 6 - String
You can use this package in flutter ReCase It gives you various case conversion functionalities like:
-
snake_case
-
dot.case
-
path/case
-
param-case
-
PascalCase
-
Header-Case
-
Title Case
-
camelCase
-
Sentence case
-
CONSTANT_CASE
ReCase sample = new ReCase('hello world'); print(sample.sentenceCase); // Prints 'Hello world'
Solution 7 - String
Super late, but I use,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...
Solution 8 - String
As mentioned before by Ephenodrom, you can add basic_utils package in your pubspeck.yaml and use it in your dart files like this:
StringUtils.capitalize("yourString");
That's acceptable for a single function, but in a larger chain of operations, it becomes awkward.
As explained in Dart language documentation:
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())
That code is much less readable than:
something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()
The code is also much less discoverable because an IDE can suggest doMyStuff()
after something.doStuff()
, but will be unlikely to suggest putting doMyOtherStuff(…)
around the expression.
For these reasons, I think you should add an extension method to String type (you can do it since dart 2.6!) like this:
/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}
and call it using dot notation:
'yourString'.capitalized()
or, if your value can be null, replacing the dot with a '?.' in the invocation:
myObject.property?.toString()?.capitalized()
Solution 9 - String
void allWordsCapitilize (String str) {
return str.toLowerCase().split(' ').map((word) {
String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
return word[0].toUpperCase() + leftText;
}).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test
Solution 10 - String
To check for null and empty string cases, also using the short notations:
String capitalizeFirstLetter(String s) =>
(s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;
Solution 11 - String
String capitalize(String s) => (s != null && s.length > 1)
? s[0].toUpperCase() + s.substring(1)
: s != null ? s.toUpperCase() : null;
It passes tests:
test('null input', () {
expect(capitalize(null), null);
});
test('empty input', () {
expect(capitalize(''), '');
});
test('single char input', () {
expect(capitalize('a'), 'A');
});
test('crazy input', () {
expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});
Solution 12 - String
you can you use capitalize() method of the strings librarie, it's now availabe in the 0.1.2 version, and make sure to add the dependencie in the pubspec.yaml:
dependencies:
strings: ^0.1.2
and import it into the dart file :
import 'package:strings/strings.dart';
and now you can use the method which has the following prototype:
String capitalize(String string)
Example :
print(capitalize("mark")); => Mark
Solution 13 - String
You should also check if the string is null or empty.
String capitalize(String input) {
if (input == null) {
throw new ArgumentError("string: $input");
}
if (input.length == 0) {
return input;
}
return input[0].toUpperCase() + input.substring(1);
}
Solution 14 - String
This is another alternative to capitalize Strings in dart with the use of the String class Method splitMapJoin
:
var str = 'this is a test';
str = str.splitMapJoin(RegExp(r'\w+'),onMatch: (m)=> '${m.group(0)}'.substring(0,1).toUpperCase() +'${m.group(0)}'.substring(1).toLowerCase() ,onNonMatch: (n)=> ' ');
print(str); // This Is A Test
Solution 15 - String
Weird this is not available in dart to begin with. Below is an extension to capitalize a String
:
extension StringExtension on String {
String capitalized() {
if (this.isEmpty) return this;
return this[0].toUpperCase() + this.substring(1);
}
}
It checks that the String
is not empty to begin with, then it just capitalizes the first letter and adds the rest
Usage:
import "path/to/extension/string_extension_file_name.dart";
var capitalizedString = '${'alexander'.capitalized()} ${'hamilton, my name is'.capitalized()} ${'alexander'.capitalized()} ${'hamilton'.capitalized()}');
// Print result: "Alexander Hamilton, my name is Alexander Hamilton"
Solution 16 - String
This code works for me.
String name = 'amina';
print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});
Solution 17 - String
Use characters rather than code units
As described in the article Dart string manipulation done right (see Scenario 4), whenever you are dealing with user input you should use characters
rather than the index.
// import 'package:characters/characters.dart';
final sentence = 'e\u0301tienne is eating.'; // étienne is eating.
final firstCharacter = sentence.characters.first.toUpperCase();
final otherCharacters = sentence.characters.skip(1);
final capitalized = '$firstCharacter$otherCharacters';
print(capitalized); // Étienne is eating.
In this particular example it would still work even if you were using the index, but it's still a good idea to get into the habit of using characters
.
The characters package comes with Flutter so there is no need for the import. In a pure Dart project you need to add the import but you don't have to add anything to pubspec.yaml.
Solution 18 - String
extension StringExtension on String {
String capitalize() {
return this
.toLowerCase()
.split(" ")
.map((word) => word[0].toUpperCase() + word.substring(1, word.length))
.join(" ");
}
}
For anyone interested, this should work on any string
Solution 19 - String
var orig = "this is a string";
var changed = orig.substring(0, 1).toUpperCase + orig.substring(1)
Solution 20 - String
Some of the more popular other answers don't seem to handle null
and ''
. I prefer to not have to deal with those situations in client code, I just want a String
in return no matter what - even if that means an empty one in case of null
.
String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
Solution 21 - String
You can use the Text_Tools package, is simple to use:
https://pub.dev/packages/text_tools
Your code would be like this:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
Solution 22 - String
The simplest answer is here:
First make the string's first letter to uppercase using its index then concate the rest of the string.
Here username is the string.
username[0].toUpperCase() + username.substring(1);
Solution 23 - String
I've used Hannah Stark answer, but it crashes the app, if the string is empty, so here is improved version of the solution with the extension:
extension StringExtension on String {
String capitalize() {
if(this.length > 0) {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
return "";
}
}
Solution 24 - String
String fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
Solution 25 - String
Here is my answer using dart String methods.
String name = "big";
String getFirstLetter = name.substring(0, 1);
String capitalizedFirstLetter =
name.replaceRange(0, 1, getFirstLetter.toUpperCase());
print(capitalizedFirstLetter);
Solution 26 - String
Herewith Sharing my answer
void main() {
var data = allWordsCapitilize(" hi ram good day");
print(data);
}
String allWordsCapitilize(String value) {
var result = value[0].toUpperCase();
for (int i = 1; i < value.length; i++) {
if (value[i - 1] == " ") {
result = result + value[i].toUpperCase();
} else {
result = result + value[i];
}
}
return result;
}
Solution 27 - String
Another unhealthy way I found of solving this issue is to
String myName = "shahzad";
print(myName.substring(0,1).toUpperCase() + myName.substring(1));
this will produce the same effect but is pretty dirty way of doing it.
Solution 28 - String
I used a different implementation:
- Create a class:
import 'package:flutter/services.dart';
class FirstLetterTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
return TextEditingValue(
//text: newValue.text?.toUpperCase(),
text: normaliseName(newValue.text),
selection: newValue.selection,
);
}
/// Fixes name cases; Capitalizes Each Word.
String normaliseName(String name) {
final stringBuffer = StringBuffer();
var capitalizeNext = true;
for (final letter in name.toLowerCase().codeUnits) {
// UTF-16: A-Z => 65-90, a-z => 97-122.
if (capitalizeNext && letter >= 97 && letter <= 122) {
stringBuffer.writeCharCode(letter - 32);
capitalizeNext = false;
} else {
// UTF-16: 32 == space, 46 == period
if (letter == 32 || letter == 46) capitalizeNext = true;
stringBuffer.writeCharCode(letter);
}
}
return stringBuffer.toString();
}
}
Then you import the class into any page you need eg in a TextField's inputFormatters property, just call the widget above like so:
TextField(
inputformatters: [FirstLetterTextFormatter()]),
),
Solution 29 - String
You can use this one:
extension EasyString on String {
String toCapitalCase() {
var lowerCased = this.toLowerCase();
return lowerCased[0].toUpperCase() + lowerCased.substring(1);
}
}
Solution 30 - String
In range checked.
Idiomatic as of Dart >2.16.1
As a function
String capitalize(String str) =>
str.isNotEmpty
? str[0].toUpperCase() + str.substring(1)
: str;
As an extension
extension StringExtension on String {
String get capitalize =>
isNotEmpty
? this[0].toUpperCase() + substring(1)
: this;
}
Solution 31 - String
As of 23/3/2021 Flutter 2.0.2
Just use yourtext.capitalizeFirst
Solution 32 - String
Try this code to Capitalize of first letter of any String in Dart - Flutter
Example: hiii how are you
Code:
String str="hiii how are you";
Text( '${str[0].toUpperCase()}${str.substring(1)}',)`
Output: Hiii how are you
Solution 33 - String
final helloWorld = 'hello world'.toUpperCase(); Text(helloWorld);