Hello friends, In today’s tutorial we would learn about stretch to fit, Auto text size functionality in flutter. In few applications sometimes we have to make Auto Resize text widget, Where we don’t have to define Text font size and it will adapt text size automatically as per Container width height. This is pretty cool. Text automatically resize itself. In flutter this can be possible via FittedBox widget. The FittedBox widget Creates a widget that scales and positions its child within itself according to given parent Width Height. So in this tutorial we would learn about Stretch Text Size as Container Width Height Allow in Flutter.
Example of Stretch Text Size as Container Width Height Allow in Flutter :-
1. Open your project’s main.dart file and import material.dart package.
1 |
import 'package:flutter/material.dart'; |
2. Creating void main runApp() method and here we would call our main MyApp class.
1 |
void main() => runApp(MyApp()); |
3. Creating main class MyApp extends StatelessWidget.
1 2 3 4 5 6 |
class MyApp extends StatelessWidget { } |
4. Creating Widget Build area -> Here we would first make 1 Root Container widget -> Make FittedBox widget as its child and put the Text widget inside it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: SafeArea( child: Center( child: Container( color: Colors.cyanAccent, width: 200.0, height: 200.0, child: const FittedBox( fit: BoxFit.contain, child: Text("Hello"), ), ), ))))); } |
5. Complete source code for main.dart file :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: SafeArea( child: Center( child: Container( color: Colors.cyanAccent, width: 200.0, height: 200.0, child: const FittedBox( fit: BoxFit.contain, child: Text("Hello"), ), ), ))))); } } |
Screenshot :-