ConstrainedBox 中的 Flutter 图标小部件

Flutter icon widget in ConstrainedBox

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Container(
          child: ConstrainedBox(
            constraints: BoxConstraints(
              maxHeight: 100,
              maxWidth: 100,
            ),
            child: Icon(
              Icons.backup,
              size: 200,
            ),
          ),
        ));
  }
}

在上面的代码中,如果我用图像或文本替换图标小部件,它们将停留在 ConstrainedBox 边界,但图标会变成全尺寸!为什么?

您可以复制粘贴 运行 下面的完整代码
因为在Icon的源代码中,它实际上使用了RichTextTextOverflow.visible
源代码 link https://github.com/flutter/flutter/blob/8df56056b4914060784e68e6b149a30319b75d3d/packages/flutter/lib/src/widgets/icon.dart#L174

源代码代码片段

Widget iconWidget = RichText(
  overflow: TextOverflow.visible, // Never clip.
  textDirection: textDirection, // Since we already fetched it for the assert...
  text: TextSpan(
    text: String.fromCharCode(icon!.codePoint),
    style: TextStyle(
      inherit: false,
      color: iconColor,
      fontSize: iconSize,
      fontFamily: icon!.fontFamily,
      package: icon!.fontPackage,
    ),
  ),
);

工作演示使用 RichText

完整代码使用 RichText

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHome(),
    );
  }
}

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Container(
          child: ConstrainedBox(
              constraints: BoxConstraints(
                maxHeight: 100,
                maxWidth: 100,
              ),
              child: RichText(
                overflow: TextOverflow.visible, // Never clip.
                //textDirection: textDirection, // Since we already fetched it for the assert...
                text: TextSpan(
                  text: String.fromCharCode((Icons.backup).codePoint),
                  style: TextStyle(
                    inherit: false,
                    color: Colors.blue,
                    fontSize: 200,
                    fontFamily: (Icons.backup).fontFamily,
                    package: (Icons.backup).fontPackage,
                  ),
                ),
              )),
        ));
  }
}