Flutter: how to fit widget with aspect ratio inside its parent?

Viewed 1620

I want have two widgets center in a container.

Widget A with aspect ratio 1:1 and fitting in container.

Widget B is a Text with its height fitting is content and its width filling parent.

For example:

In portrait mode

enter image description here

In landscape mode

enter image description here

Here is the code that I tried:

  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                flex: 1,
                child: Container(
                  color: Colors.deepPurple,
                  child: AspectRatio(
                    aspectRatio: 1 / 1,
                    child: Container(color: Colors.yellow),
                  ),
                )),
            Container(
                color: Colors.green,
                child: Center(child: Text("TEST", textAlign: TextAlign.center)))
          ],
        ));
  }

But result is like this:

In portrait mode

enter image description here

In landscape mode

enter image description here

Widget A is filling all spaces in portrait mode instead of fitting inside.

How to make Widget A fitting in container?

1 Answers

I have made some changes. You can try this. Maybe this is not the right and efficient way. But you can try it.

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    //Calculate width and height as your wish
    double width = size.width < size.height ? size.width : size.height * .5;
    double height = width * 1.1;
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              color: Colors.deepPurple,
              child:
                  Container(width: width, height: height, color: Colors.yellow),
            ),
            Container(
                color: Colors.green,
                child: Center(child: Text("TEST", textAlign: TextAlign.center)))
          ],
        ));
  }
Related