I'm trying to use BoxFit.scaleDown in a FittedBox's fit property to scale the font down in a Text widget to accommodate strings of varying length.
However, the below code will scale down the entire string and make it fit on one line, For the below example, I would like the font scaled down so that the string can fit on two lines (per maxLines property of the Text widget).
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Multi-Line Label Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Multi-Line Label Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final textStyle = const TextStyle(fontSize: 28.0);
final text =
'Lorem Ipsum is simply dummy text of the printing and typesetting'
'industry. Lorem Ipsum has been the industry\'s standard dummy text'
'ever since the 1500s, when an unknown printer took a galley of type'
'and scrambled it to make a type specimen book.';
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FittedBox(
fit: BoxFit.scaleDown,
child: new Text(
text,
maxLines: 2,
style: textStyle,
textAlign: TextAlign.center,
),
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*eev 31
一个简单的插入式解决方案是使用FittedBox具有fit: BoxFit.scaleDown:
Container(
width: 100.0,
child: FittedBox(
fit: BoxFit.scaleDown,
// Optionally apply `alignment` to position the text inside the box:
//alignment: Alignment.topRight,
child: SizedBox(
child: Text('\$1,299.99'),
)
)
Run Code Online (Sandbox Code Playgroud)
根据您想要的限制,我们有 2 个现成的解决方案。
如果您喜欢布局在某些参考屏幕尺寸上的外观,想要将文本区域视为一个框,并且在给定其他尺寸的屏幕的情况下放大或缩小整个框,则此解决方案有效。
获取参考屏幕。按预期布置所有内容。找出包含文本的框的大小(例如,通过在调试期间按“t”来显示渲染树)。然后用与SizedBox测量相同大小的a 包裹包含文本框的文本。然后用你的FittedBox.
限制基本上是您的文本在所有屏幕上的布局方式完全相同,并且文本框的纵横比相同。
给定大小可变LayoutBuilder的父级,在运行时首先使用 a获取父级的大小,然后手动调整子文本小部件中的字体大小以确保它适合。
文本布局更加流畅,包含框可以有不同的纵横比,但您必须检查与您拥有的字体大小开关一样多的屏幕大小。尽管使用小部件测试很容易确保文本不会在任何屏幕尺寸下溢出
如果有更多涉及依赖字体缩放的通用用例的具体示例,我们还可以创建更复杂但自动的方法
您可以使用自动文本包
https://pub.dartlang.org/packages/auto_size_text
安装后,只需将所有“文本”替换为“ AutoSizeText”,您会发现一切都会很好:)
| 归档时间: |
|
| 查看次数: |
5624 次 |
| 最近记录: |