Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize text in Flutter

Tags:

text

flutter

I tried to find how capitalize text in Flutter, but I couldn't find it.

My code:

Center(
    heightFactor: 2,
    child: Text(
      'Strengthening the bond of owners and pets, more than ever...',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 20.0,
        fontStyle: FontStyle.italic,
        fontWeight: FontWeight.bold,
        color: Colors.cyanAccent[700],
        wordSpacing: 8,
      ),
    )),
like image 712
Mukha Avatar asked Jan 21 '26 05:01

Mukha


2 Answers

I dont know if there is a way to do it through the Text widget, but you can use string.toUppercase() to capitalize the word:

Center(
heightFactor: 2,
child: Text(
  'Strengthening the bond of owners and pets, more than ever...'.toUpperCase(),
  textAlign: TextAlign.center,
  style: TextStyle(
    fontSize: 20.0,
    fontStyle: FontStyle.italic,
    fontWeight: FontWeight.bold,
    color: Colors.cyanAccent[700],
    wordSpacing: 8,
  ),
)),

UPDATE:

To capitalize just the first letter of the String you can simply add an extension like this:

extension StringExtension on String {
  String capitalize() {
     return 
       "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
  }
}

and call it anywhere like this:

'string'.capitalize()
like image 142
Bensal Avatar answered Jan 23 '26 14:01

Bensal


To capitalize and to uppercase are different:

  • Capitalize: "Strengthing..."
  • Uppercase: "STRENGTHING..."

Capitalize

To capitalize a string in all locales:

import 'package:intl/intl.dart';

toBeginningOfSentenceCase('strengthening...');

To capitalize a string for en-US like locales:

String text = 'strengthening...';
text = text[0].toUpperCase() + text.substring(1).toLowerCase();

You can also have the virtual keyboard automatically switch to uppercase on the start of a sentence:

TextField(
  textCapitalization: TextCapitalization.sentences
)

https://api.flutter.dev/flutter/services/TextCapitalization.html

Uppercase

To uppercase a string:

'strengthening...'.toUpperCase()

You can also have the virtual keyboard automatically switch to uppercase on each character

TextField(
  textCapitalization: TextCapitalization.characters
)

https://api.flutter.dev/flutter/services/TextCapitalization.html

like image 25
tim-montague Avatar answered Jan 23 '26 12:01

tim-montague



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!