dart - 如何自动缩小文本小部件中的字体以适应最大行数?

我正在尝试使用 BoxFit.scaleDownFittedBox的 fit 属性在 Text 中缩小字体小部件以适应不同长度的字符串。

但是,下面的代码将缩小整个字符串并使其适合一行,对于下面的示例,我希望缩小字体以便字符串可以适合两行(根据 maxLines 的属性Text 小部件)。

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,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

最佳答案

一个简单的解决方案是使用 FittedBoxfit: 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'),
  )
)

https://stackoverflow.com/questions/47665083/

相关文章:

flutter - 在 flutter 中使用 TabBarView 获取 'Horizontal

android - 在 flutter 中从 initState 调用 scopedModel

flutter - Flutter中有类似AlarmManager的东西吗?

android - Flutter Multiline 文本

android - Flutter 未检测到 Android SDK

java - 使用 Platform Channels 在 Flutter 中调用原生库

dart - 如何从 Flutter 检查设备操作系统版本?

dart - Material Flutter 应用源码

flutter - 在 Flutter 中选择下拉项时出错

firebase - 如何使用 Firebase 身份验证在 Flutter 中注销用户