sriba
sriba

Reputation: 775

Flutter: Horizontal ListView view with different height contraint

I have a horizontal list bar with fixed height 100 (used inside Column). Height 100 is good for iPhone8. But the pixel overflows in iPhone-X due to limited 100 height. If I make it 140, both are good. But the bar looks no good in iphone8. So I want 120 height in one device and 140 in other device. I thought I could achieve it using ConstrainedBox like below:

ConstrainedBox(constraints: BoxConstraints(minHeight: 100, maxHeight: 140), child: ListView(...))

But listview goes with 140 height all the time. So How to achive dynamic height contraint for different device?

Sample widget:

class MyHorizontalBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 100, // 140
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          _myCard(),
          _myCard(),
          _myCard(),
        ],
      ),
    );
  }

  Widget _myCard(){
    return Container(
      width: 115,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Top', style: TextStyle(fontSize: 12)),
          Text('Middle', style: TextStyle(fontSize: 25)),
          Text('Bottom', style: TextStyle(fontSize: 18)),
        ],
      ),
    );
  }
}

Upvotes: 0

Views: 353

Answers (3)

Nuwan Sampath
Nuwan Sampath

Reputation: 1

Use MediaQuery.of(context)

try the following code.

class MyHorizontalBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double magicNumber = 5; // Try playing with this number to get the appearence. 
    return SizedBox(
      height: MediaQuery.of(context).size.height / magicNumber, 
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          _myCard(),
          _myCard(),
          _myCard(),
        ],
      ),
    );
  }

  Widget _myCard() {
    return Container(
      width: 115,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
              Text('Top', style: TextStyle(fontSize: 12)),
              Text('Middle', style: TextStyle(fontSize: 25)),
              Text('Bottom', style: TextStyle(fontSize: 18)),
            ],
          ),
        );
      }
    }

Try playing with the variable magicNumber.

Upvotes: 0

Rustem Kakimov
Rustem Kakimov

Reputation: 2671

You can use LayoutBuilder widget. But such problems are usually solved with a flexible layout.

e.g. defining your horizontal bar height as 1/3 of available height.

Upvotes: 0

C.M Talha
C.M Talha

Reputation: 383

Try using MediaQuery.of(context).size.height or width in place of constant height and width.

Upvotes: 1

Related Questions