Flutter – Programmatically Change Font Size

Change Font Size Programmatically in Flutter

In this tutorial, we will change the font size of Text widget programmatically/dynamically.

Follow these steps to change the font size of Text widget programmatically.

  1. Create a variable of type double in State class. This will be used for fontSize.
  2. When you create Text widget in build function, set style with the variable created in the previous step.
  3. Now, you can update the fontSize variable on a button click or some

Example

This example Flutter application demonstrates how to change the font size programmatically or dynamically.

To recreate this example, create a Flutter project and replace the main.dart with the following code.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  double custFontSize = 20;

  void changeFontSize() async{
    setState(() {
      custFontSize+=2;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tutorial - googleflutter.com'),
      ),
      body: Center(
          child: Column(children: <Widget>[
            Text('Welcome to Flutter Tutorial',
              style: TextStyle(fontSize: custFontSize),
            ),
            RaisedButton(
              onPressed: () {
                changeFontSize();
              },
              child: Text('Change size'),
            ),
          ])),
    );
  }
}

When you run this example Flutter application, you would get a text widget and a button as shown in the following screenshot. And when you click on the button, the font size increases by 2 for each click.

Change Font Size Programmatically in Flutter

Summary

In this Flutter Tutorial, we have learned how to change the font size of Text widget programmatically/dynamically.

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.