Skip to content

Instantly share code, notes, and snippets.

@suragch
Created June 4, 2024 06:01
Show Gist options
  • Save suragch/cd0e9bf48e107e155913d1b2fe0c3ecc to your computer and use it in GitHub Desktop.
Save suragch/cd0e9bf48e107e155913d1b2fe0c3ecc to your computer and use it in GitHub Desktop.
ScalableText
class ScalableText extends StatefulWidget {
const ScalableText(
this.text, {
required this.fontSize,
this.onTextScaled,
Key? key,
}) : super(key: key);
final TextSpan text;
final double fontSize;
final ValueSetter<double>? onTextScaled;
@override
State<ScalableText> createState() => _ScalableTextState();
}
class _ScalableTextState extends State<ScalableText> {
double _fontSize = 30.0;
double _baseFontSize = 30.0;
double _fontScale = 1;
double _baseFontScale = 1;
@override
void initState() {
_baseFontSize = widget.fontSize;
_fontSize = _baseFontSize;
super.initState();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onScaleStart: (ScaleStartDetails details) {
_baseFontScale = _fontScale;
},
onScaleUpdate: (ScaleUpdateDetails scaleUpdateDetails) {
// don't update the UI if the scale didn't change
if (scaleUpdateDetails.scale == 1.0) {
return;
}
_fontScale =
(_baseFontScale * scaleUpdateDetails.scale).clamp(0.5, 5.0);
setState(() {
_fontSize = _fontScale * _baseFontSize;
});
},
onScaleEnd: (ScaleEndDetails details) {
// don't update the UI if the font size didn't change
if (_fontScale == _baseFontScale) {
return;
}
widget.onTextScaled?.call(_fontSize);
},
child: MongolText.rich(
widget.text,
style: TextStyle(fontSize: _fontSize),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment