如何在扑动动态调整文本大小?

我从一个 API 检索一段文本。我想为它分配一定的空间量(比如宽度为300.0,高度为100.0的 max Container)。有时,这段文字适合这个容器的字体大小为30.0。在其他情况下,除非我将文本大小设置为24.0,否则它就不适合。

是否有办法根据其父容器空间动态调整文本的大小?

我用 ConstrainedBox 构建了一个 Container,它允许我定义文本空间的最大大小。我还用 LayoutBuilder 包装了我的文本。我希望能够检查文本的空间高度,并基于此确定如何调整文本的大小。像这样:

    Container(
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: 300.0,
maxWidth: 300.0,
minHeight: 30.0,
maxHeight: 100.0,
),
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (/* height is larger than 100.0? height is over the constraints? */) { return textWithSize24(); }
return textWithSize30();
}),
),
),

如何确定“如果文本大小为30.0,则文本将占用的高度”? 也许我的方法不对,我应该用 maxLines来确定这个?但是我们怎么知道我们已经超过了 maxLines

另一种方法是使用 String 中的字符数来确定何时更改字体大小。这看起来像是手动操作。

189510 次浏览

下面是我尝试过的一些东西,它们可能对你有用,这取决于你的用例: https://github.com/flutter/flutter/issues/18431

最后,我使用了一个函数,该函数根据 String 的长度设置字体大小(例如,使用 if-else 语句)。

你可以使用 Auto _ size _ text软件包:

Container(
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: 300.0,
maxWidth: 300.0,
minHeight: 30.0,
maxHeight: 100.0,
),
child: AutoSizeText(
"yourText",
style: TextStyle(fontSize: 30.0),
),
),
);

如果只想允许特定的字体大小,还可以设置 maxLines以进一步约束文本或使用 presetFontSizes

可以使用 FittedBox根据高度或宽度管理文本。

为了前任。

只需将 Text小部件包装到 FittedBox小部件即可,比如,这里我想根据宽度调整 AppBar 文本的大小。

AppBar(
centerTitle: true,
title: FittedBox(
fit: BoxFit.fitWidth,
child: Text('Hey this is my long text appbar title')
),
),


文本将根据 AppBar 的宽度调整大小。

只需根据文本长度和最大呈现面积生成字体大小即可。在您的情况下 300.0 * 100.0,不要忘记在渲染文本过程中丢失的区域。

像这样:

class MyWidget extends StatefulWidget {
@override
_StateMyWidget createState() => _StateMyWidget();
}


class _StateMyWidget extends State<MyWidget> {
static const _QUOTES = [
{"quote": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm", "author": "test"},
{"quote": "Talk is cheap. Show me the code.", "author": "Linus Torvalds"},
{"quote": "First, solve the problem. Then, write the code.", "author": "John Johnson"},
{"quote": "To iterate is human, to recurse divine.", "author": "L. Peter Deutsch"},
{"quote": "The best thing about a boolean is even if you are wrong, you are only off by a bit.", "author": "Anonymous"},
{"quote": "Software is like sex: It’s better when it’s free.", "author": "Linus Torvalds"},
{"quote": "The first 90% of the code accounts for the first 90% of the development time.  The remaining 10% of the code accounts for the other 90% of the development time.", "author": "Tom Cargill"},
{"quote": "I think that it’s extraordinarily important that we in computer science keep fun in computing. When it started out it was an awful lot of fun. Of course the paying customers got shafted every now and then and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful error-free perfect use of these machines. I don’t think we are. I think we’re responsible for stretching them setting them off in new directions and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all I hope we don’t become missionaries. Don’t feel as if you’re Bible sales-men. The world has too many of those already. What you know about computing other people will learn. Don’t feel as if the key to successful computing is only in your hands. What’s in your hands I think and hope is intelligence: the ability to see the machine as more than when you were first led up to it that you can make it more.", "author": "Alan J. Perlis"},
{"quote":"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live","author": "John Woods"},
{"quote":"You've baked a really lovely cake, but then you've used dog shit for frosting.","author": "Steve Jobs"},
{"quote": "Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.","author": "Alan Kay" },
{"quote": "Software suppliers are trying to make their software packages more ‘user-friendly’…  Their best approach so far has been to take all the old brochures and stamp the words ‘user-friendly’ on the cover.","author": "Bill Gates"},
];


static const AREA_LOST_PERCENT = 5;


final rand = math.Random();


@override
initState() {
super.initState();
Timer.periodic(Duration(seconds: 3), (timeVal) {
setState(() {});
});
}


@override
Widget build(BuildContext context) {
final Map<String, String> mapQuote = _QUOTES[rand.nextInt(_QUOTES.length)];


final authorW =
Text(mapQuote["author"], style: TextStyle(fontStyle: FontStyle.italic));


final quoteW = Text(
mapQuote["quote"],
textAlign: TextAlign.center,
style: TextStyle(
fontSize: autoSize(
quoteLength: mapQuote["quote"].length,
parentArea: (350 - 10 * 2 - 16 * 2) * (450 - 10 * 2),
),
),
);


final containerW0 = Container(
height: 450.0,
padding: EdgeInsets.all(10.0),
color: Colors.grey,
child: Center(child: quoteW));


final containerW1 = Container(
height: 500.0,
width: 350,
padding: EdgeInsets.all(16.0),
color: Colors.purple,
child: Column(children: [authorW, containerW0]));


return containerW1;
}


double autoSize({@required int quoteLength, @required int parentArea}) {
assert(quoteLength != null, "`quoteLength` may not be null");
assert(parentArea != null, "`parentArea` may not be null");
final areaOfLetter = parentArea / quoteLength;
final pixelOfLetter = math.sqrt(areaOfLetter);
final pixelOfLetterP = pixelOfLetter - (pixelOfLetter * AREA_LOST_PERCENT) / 100;
return pixelOfLetterP;
}
}

在分配丢失区域的百分比时,必须考虑转义字符。如果变化过大,最好去除它们。

在线视图-> dartpad.dev

使用 BoxFit.scaleDown和固定的 FontSize,你可以调整字体的最大大小。

如果内容较小,则使用指定的字体大小占用最小宽度。同时,如果内容很大,它会调整到最小的字体大小。

FittedBox(
fit: BoxFit.scaleDown,
child:
Text(
"Text here",
style: TextStyle(fontSize: 18),
),)

如果你需要文字来填充整个宽度,使用任何字体大小使用 BoxFit.cover

FittedBox(
fit: BoxFit.cover,
child:
Text(
"Text here",
//style: TextStyle(fontSize: 18),
),)

Responsive _ Flutter ,自从读到你的问题后,我也遇到了同样的问题。我发现它 屡试不爽使用这个软件包来调整你的字体大小。

这个 Flutter 软件包用于在不同大小的设备上缩放应用程序 UI 和 fontSize的大小。(示例显示了使用 Responsive _ Flutter 包的顶部文本和没有插件的底部文本。

Https://github.com/layounisl/responsive_flutter

您可以在30秒内安装-3个步骤

  1. 向 yaml 文件 responsive_flutter: ^0.0.4添加依赖项
  2. import 'package:responsive_flutter/responsive_flutter.dart';
  3. child: Text("Responsive flutter", style: TextStyle(fontSize: ResponsiveFlutter.of(context).fontSize(3)),

App using Flutter

我发现最简单的事情是 auto_size_text: ^2.1.0。就像导入依赖项并使用 AutoSizeText()而不是 Text()一样简单

import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';


void main() {
runApp(App());
}


class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SizedBox(
width: 200.0,
height: 140.0,
child: AutoSizeText(
'This string will be automatically resized to fit in two lines.',
style: TextStyle(fontSize: 30.0),
maxLines: 2,
),
),
),
),
);
}
}

您还可以使用 MediaQueryData类中的 textScaleFactor属性来限制文本的大小

FittedBox 在我的案例中使用了多行代码。

SizedBox(
width: MediaQuery.of(context).size.width,
child: FittedBox(
fit: BoxFit.contain,
child: Text(
widget.model.poem,
textAlign: TextAlign.justify,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontStyle: FontStyle.normal),
),
),
),

有两种方法可以做到这一点。

  1. 使用 FittedBox
  2. 使用 TextPainter (使用文本 Painter 计算宽度 及更新字体)

Https://prafullkumar77.medium.com/how-to-dynamically-resize-text-in-flutter-bca80415a4d2

我这样使用,效果非常好:

Flexible(
child: FittedBox(
fit: BoxFit.contain,
child: AutoSizeText(
'your specific text',
maxLines: 1,
style: TextStyle(),
),
),
),

这样除了使用 < a href = “ https://pub.dev/package/auto _ size _ text”rel = “ nofollow norefrer”> auto _ size _ text 之外,还提供了 灵活性,并确保我们的子窗口小部件在其中并且按照预期的方式运行(包含)。