Search code examples
dartflutterflutter-layout

Center Expanded ListView inside Column Flutter


I'm trying to build a layout where there are two Text objects at the top and bottom which stays stationery and a ListView at their center.

Here's the code for the Screen

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 40.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                margin: EdgeInsets.symmetric(vertical: 40.0),
                child: Text(
                  DateFormat("hh:mm 'PM ,'  MMMM d").format(DateTime.now()),
                  style: Theme.of(context).textTheme.title,
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: 4,
                  itemBuilder: (BuildContext context, int index) =>
                      CustomAppText(
                        text: 'Custom App',
                      ),
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(vertical: 40.0),
                child: Text(
                  "Settings",
                  style: Theme.of(context).textTheme.title,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The output of the given code Output of given code

The Design I'm looking for Desired output

I have tried using the Center widget but it does not center the ListView


Solution

  • The ListView fills the entire Expanded Widget, that's why using the Center widget didn't work, so shrinkWrap: true should be added so the ListView takes only the height of it's children.

    After skimming through the documentation I found about Flexible Widget

    Flexible, which does not force the child to fill the available space.
    

    Made the change and works like a charm

    Flexible(
      child: ListView.builder(
      shrinkWrap: true,
      itemCount: 4,
      itemBuilder: (BuildContext context, int index) =>
        CustomAppText(
          text: 'Custom App',
        ),
      ),
    ),