Want to replace text if it will overflow in flutter? The idea is that you use LayoutBuilder to wrap your widget, thus getting the BoxConstraints and using that you can use TextPainter to determine if the text would fit in the given BoxConstraints.
Here is a working example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Text Overflow Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar(title: Text("DEMO")), body: TextOverflowDemo(), ), ); } } class TextOverflowDemo extends StatelessWidget { @override Widget build(BuildContext context) { int maxLines = 1; return Container( color: Colors.white, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 60.0),// set maxWidth to a low value to see the result child: LayoutBuilder(builder: (context, size) { String text = 'January 1, 2019'; var exceeded = doesTextFit(text, maxLines, size); return Column(children: <Widget>[ Text( exceeded ? '1/1/2019' : text, overflow: TextOverflow.ellipsis, maxLines: maxLines, ), ]); }), ), ); } bool doesTextFit(String text, int maxLines, BoxConstraints size, {TextStyle textStyle}) { TextSpan span; if (textStyle == null) { span = TextSpan( text: text, ); } else { span = TextSpan(text: text, style: textStyle); } TextPainter tp = TextPainter( maxLines: maxLines, textAlign: TextAlign.left, textDirection: TextDirection.ltr, text: span, ); tp.layout(maxWidth: size.maxWidth); return tp.didExceedMaxLines; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.