Search code examples
androidflutterdartscroll

Page is not Scrolling Fully because of Expanded


When I remove SingleChildScrollView and use the property physics: const NeverScrollableScrollPhysics(), The code works fine and the scrolling works, But by doing this I the scroll only works for this widget NewsItem which is at the end of the page and the scroll is actually working only for the NewsItem rather for the whole page which Is what I wanna acheive.

Here is the code,

body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 18.0),
          child: Column(
            children: [
            // .... Some Widgets that take the 70% of the screen 
              Expanded(
                // height: 500,
                child: ListView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  scrollDirection: Axis.vertical,
                  itemCount: 5,
                  itemBuilder: (ctx, idx) {
                    return const NewsItem(
                      image:
                          'https://media.giphy.com/media/fTn01fiFdTd5pL60ln/giphy.gif',
                      headline: "Joe was attacked again! Lmaooooo",
                      author: 'Jack Williams',
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),

By wrapping the NewsItem with the Expanded widget leaves no room for scroll unless I replace it with SizedBox But it only enables for me to scroll down the whole page where am seeing 3 of the NewsItem instead of 5 as written.


Solution

  • You can simplify things by using the spread operator ... to add a generated list of widgets:

    body: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 18.0),
      child: ListView(
        children: [
          // .... Some Widgets that take the 70% of the screen
          // Use the spread operator to add a generated list of NewsItems with length 5
          ...List<Widget>.generate(
            5,
            (index) {
              // [index] is the position in the generated list (from 0 up to 4 in this case)
              return const NewsItem(
                image: 'https://media.giphy.com/media/fTn01fiFdTd5pL60ln/giphy.gif',
                headline: 'Joe was attacked again! Lmaooooo',
                author: 'Jack Williams',
              );
            },
          ),
        ],
      ),
    ),