How to capitalize text in Flutter

2,377

Solution 1

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,
  ),
)),

Solution 2

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

Share:
2,377
Mukha
Author by

Mukha

Updated on December 24, 2022

Comments

  • Mukha
    Mukha over 1 year

    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,
          ),
        )),
    
  • tim-montague
    tim-montague over 2 years
    @bensel - this is not capitalization, it's uppercase
  • Bensal
    Bensal over 2 years
    @tim-montague but i hope i have answered his question