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.
- Create a variable of type double in State class. This will be used for fontSize.
- When you create Text widget in build function, set style with the variable created in the previous step.
- 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.
Summary
In this Flutter Tutorial, we have learned how to change the font size of Text widget programmatically/dynamically.