Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Container height equal to width in Flutter

Tags:

flutter

I am learning Flutter development. I want to display some rounded square shaped containers with short text in a row. However, the possible shapes are either a circle or rectangle. So I decided to set the width and height of the rectangle so that they would be equal. The following is the code I used to create the Container

Container(
      width: double.maxFinite,
      height: 
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        color: ThemeProvider.themeOf(context).data.primaryColor,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Text(keyText),
    ),

When I set the shape in Box decoration alone, the Container resized to the size of the text. When I set the width property of the Container, I was able to divide the available width of the screen among the containers, which ensures flexibility of size if the screen was smaller or bigger, instead of hard coding it. Now I want to make the height the exact same size that the width turns out to be, thus obtaining a square container. Any idea how I could do that?

EDIT: I tried the following code and this is how the containers are looking like in both cases:

Container(
      alignment: Alignment.center,
      width: double.maxFinite,
      height: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        color: ThemeProvider.themeOf(context).data.primaryColor,
        borderRadius: BorderRadius.circular(10),
      ),

Container(
      alignment: Alignment.center,
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        color: ThemeProvider.themeOf(context).data.primaryColor,
        borderRadius: BorderRadius.circular(10),
      ),

After using MediaQuery.of(context).size.width for height property or both

like image 503
M. Abdel-Ghani Avatar asked Jun 05 '20 20:06

M. Abdel-Ghani


1 Answers

Here is a solution without using MediaQuery:

AspectRatio(
  aspectRatio: 1,
  child: Container(
    width: double.infinity,
    child: Text(),
  ),
)
like image 126
syonip Avatar answered Oct 19 '22 20:10

syonip