Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several ways to adjust font size in Flutter to fit different screen sizes:

  1. MediaQuery: You can use the MediaQuery.of() method to get the current width of the screen, and then use it to calculate the font size based on a percentage of the screen width.

Example:

double screenWidth = MediaQuery.of(context).size.width;
double fontSize = screenWidth * 0.05; // 5% of screen width
Text("Hello World", style: TextStyle(fontSize: fontSize));
  1. LayoutBuilder: You can use the LayoutBuilder widget to get the constraints of the widget that you're building, and then use that information to adjust the font size.

Example:

LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    double fontSize = constraints.maxWidth * 0.05; // 5% of box width
    return Text("Hello World", style: TextStyle(fontSize: fontSize));
  },
),
  1. ScreenUtil: You can use the ScreenUtil package, which provides a set of functions to scale UI elements based on different screen sizes and pixel densities.

Example:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Text("Hello World", style: TextStyle(fontSize: ScreenUtil().setSp(30)));

In this example, the setSp() method scales the font size to be 30 SP (scaled pixels) for the current screen size and pixel density.

Overall, choosing the best approach depends on your particular use case and design requirements.