How to capitalize the first letter of a string in dart?
Since dart version 2.6, dart supports extensions:
extension StringExtension on String { String capitalize() { return "${this[0].toUpperCase()}${this.substring(1)}"; }}
So you can just call your extension like this:
import "string_extension.dart";var someCapitalizedString = "someString".capitalize();
Copy this somewhere:
extension CapExtension on String { String get inCaps => this.length > 0 ?'${this[0].toUpperCase()}${this.substring(1)}':''; String get allInCaps => this.toUpperCase(); String get capitalizeFirstofEach => this.replaceAll(RegExp(' +'), ' ').split(" ").map((str) => str.inCaps).join(" ");}
Usage:
final helloWorld = 'hello world'.inCaps; // 'Hello world'final helloWorld = 'hello world'.allInCaps; // 'HELLO WORLD'final helloWorldCap = 'hello world'.capitalizeFirstofEach; // 'Hello World'
Old answer:
main() { String s = 'this is a string'; print('${s[0].toUpperCase()}${s.substring(1)}');}
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';...String sentence = toBeginningOfSentenceCase('this is a string'); // This is a string