fluttertext

How to capitalize text in 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,
      ),
    )),

Solution

  • 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()