Flutter icon widget in ConstrainedBox

481 Views Asked by At
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,
            ),
          ),
        ));
  }
}

in the above code, if i replace icon widget with image or text they stay at ConstrainedBox boundaries, but icon get full size! why?

icon box

1

There are 1 best solutions below

0
On BEST ANSWER

You can copy paste run full code below
Because in Icon's source code, it's actually use RichText and TextOverflow.visible
source code link https://github.com/flutter/flutter/blob/8df56056b4914060784e68e6b149a30319b75d3d/packages/flutter/lib/src/widgets/icon.dart#L174

code snippet of souce code

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

working demo use RichText

enter image description here

full code use 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,
                  ),
                ),
              )),
        ));
  }
}