Custom responsive Text widget in Flutter
import 'package:flutter/material.dart';
//ResponsiveText widget class
class ResponsiveText extends StatelessWidget {
final String text;
final double minTextSize;
final double maxTextSize;
ResponsiveText({
required this.text,
required this.minTextSize,
required this.maxTextSize,
});
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
double scaleFactor = screenWidth / 375.0; // Assuming the base screen width is 375.0 (adjust as needed)
double dynamicTextSize = max(minTextSize, min(maxTextSize, 16.0 * scaleFactor));
return Text(
text,
style: TextStyle(
fontSize: dynamicTextSize,
),
);
}
}
//******************************************************************************
// main() function
void main() {
runApp(MyApp());
}
// MyApp Widget class
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Responsive Text Example'),
),
body: Center(
child: ResponsiveText(
text: 'Hello, Flutter!',
minTextSize: 12.0,
maxTextSize: 24.0,
),
),
),
);
}
}
//************************************************************************
In this example:
ResponsiveText is a custom widget that takes the text to display (text), a minimum text size (minTextSize), and a maximum text size (maxTextSize) as parameters.
Inside the build method, we use MediaQuery to get the current screen width.
We calculate a scaleFactor based on the assumption that the base screen width is 375.0. You may adjust this value depending on your design.
The dynamicTextSize is calculated by multiplying the base font size (16.0) by the scaleFactor. We ensure that the calculated size is within the specified minimum and maximum limits.
The Text widget is then created with the calculated font size.
You can customize this example based on your specific needs and adjust the scaling logic as necessary.
Inside the build method, we use MediaQuery to get the current screen width.
We calculate a scaleFactor based on the assumption that the base screen width is 375.0. You may adjust this value depending on your design.
The dynamicTextSize is calculated by multiplying the base font size (16.0) by the scaleFactor. We ensure that the calculated size is within the specified minimum and maximum limits.
The Text widget is then created with the calculated font size.
You can customize this example based on your specific needs and adjust the scaling logic as necessary.
Thanks for reading the article...
Comments
Post a Comment