简体   繁体   中英

How can I expand a Flutter horizontal ListView to take the remaining vertical space?

My actual application involves a static portion of layout at the top of the screen, followed by a section that I would like to expand to fill the remainder of the vertical space. This bottom section would ideally be a horizontal ListView that contains vertical ListViews. To imagine this, think of a full-screen vertical ListView that contains an infinite number of cards, and then you can swipe left and right on the ListView to show different sets of cards.

In an ideal world, it would just be something like this:

return ListView.builder(
  scrollDirection: Axis.horizontal,
  itemBuilder: (context, index) {
    // logic for selecting the right vertical stack
    return ListView.builder(
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index) {
        return Card(/* ... */);
      }
    );
  }
);

This throws because the horizontal ListView was given an unbounded height. Because the remaining height is dynamic, I can't set a height directly. Tricks like the following don't work:

  • Wrapping the horizontal ListView in a Column + Expanded. (flex + wrap are mutually exclusive)
  • Using a LayoutBuilder. (the vertical max size is infinity)
  • Using MediaQuery. (that's for the screen size, not remaining space)

Anyone have any ideas how to solve this?

try to use mainAxisSize: MainAxisSize.min, in the parent column

return Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    const SizedBox(
      height: 100,
      child: Text('Hello World'),
    ),
    Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: 20,
        itemBuilder: (BuildContext context, int index) => Card(
          child: Center(
            child: Text(
              '  ${index}  ',
              style: TextStyle(fontSize: 50),
            ),
          ),
        ),
      ),
    ),
  ],
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM