Home > database >  How do I make a text element take up half the height of the parent container in flutter?
How do I make a text element take up half the height of the parent container in flutter?

Time:11-28

I have the following code:

containers.add(Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Colors.blue,
              ),
              margin: const EdgeInsets.all(10),
              width: MediaQuery.of(context).size.width/2-20,
              height: MediaQuery.of(context).size.width/2-20,
              child: Column(
                children: [
                  Text(
                    value2,
                    style: TextStyle(
                      inherit: false,
                      color: Colors.white,
                      fontSize: MediaQuery.of(context).size.width/2,
                      fontWeight: FontWeight.bold,
                    )
                  ),
                ]
              )
            ));
          });
        }
      });

The container itself goes into a list which is passed into a GridView eventually becoming a 2-wide grid down the screen. I want to make it so that the text height is half of the height of the container defined by the width and height MediaQuery.of(context).size.width/2-20. Is this possible? Thanks

CodePudding user response:

You can use Expanded together with FittedBox:

class HalfHeightText extends StatelessWidget {
  final String label;
  
  const HalfHeightText({required this.label});
  
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.blue,
      ),
      margin: const EdgeInsets.all(10),
      width: MediaQuery.of(context).size.width / 2 - 20,
      height: MediaQuery.of(context).size.width / 2 - 20,
      child: Column(
        children: [
          // ===========================================
          Expanded(
            child: FittedBox(
              fit: BoxFit.contain,
              child: Text(
                label,
                style: const TextStyle(
                  inherit: false,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const Expanded(child: SizedBox.shrink()),
          // ===========================================
        ],
      ),
    );
  }
}

Result:

HalfHeightText(label: "Text")

Text's example

CodePudding user response:

use width: MediaQuery.of(context).size.width0.50, its mean like user of width 50% or else MediaQuery.of(context).size.width0.25, mean 25%

  • Related