Home > Enterprise >  Flutter: Add some widgets in between ListView.builder and ScrollView without using shrinkWrap
Flutter: Add some widgets in between ListView.builder and ScrollView without using shrinkWrap

Time:03-20

Is it possible to add some non constrained widgets in between ListView.builder and ScrollView without using shrinkWrap: true? I need something like this:

SingleChildScrollView(
  child: Padding(
    padding: somePadding,
    child: Center(
      child: ConstrainedBox(
        constraints: someConstaints,
        child: Card(
          ListView.builder(someBuilder);
        ),
      ),
    ),
  ),
);

And I can make it with shrinkWrap: true to get something like this:

image of that I'm trying to achieve

The list is inside a centered Card and both the card and the list are scrolled as the whole Scaffold body.

The problem is, the list is expected to be really large so shrinkWrap will have noticeable effect on performance. Is there any way to achieve the same without loosing lazy building of the list?

CodePudding user response:

You should use silvers to overcome this problem and also using silvers instead of shrinkwrap enhances performance of app

CodePudding user response:

Managed to do something close to that I've wanted with Slivers. It's easy to change ScrollView to CustomScrollView and ListView.builder to SliverList with SliverChildBuilderDelegate, the problem is that everything in between should be Slivers as well.

  1. Padding is easy as it has its Sliver counterpart SliverPadding.
  2. Center and ConstrainedBox are more difficult as they seem not to have any Sliver alternatives. So I ended up achieving their effect by using LayoutBuilder (SliverLayoutBuilder is also an option) and manually calculating horizontal padding based on the viewport size and the list width I want.
  3. No solution for Card surrounding the whole list though, so instead I ended up using separate Card for each list child.

So in the end I get something like this:

LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return CustomScrollView(
          slivers: [
            SliverPadding(
              padding: EdgeInsets.symmetric(
                  vertical: PhrasememConstrains.smallPadding,
                  horizontal: (constraints.maxWidth - desiredListWidth) / 2),
              sliver: SliverList(
                delegate: SliverChildBuilderDelegate(/*some list child with card code*/),
              ),
            ),
          ],
        );
      },
);

It works, but not exactly that I wanted and it has some limitations. So I'm still hoping someone has a more elegant solution.

  • Related