11

I am trying to add a Text widget into CustomScrollView but I got issues like the target is not the same.

This is my widget:

@override
Widget build(BuildContext context) {
  final double statusBarHeight = MediaQuery.of(context).padding.top;
  return Scaffold(
      key: scaffoldKey,
      body: CustomScrollView(
        semanticChildCount: 2,
        slivers: <Widget>[
          _buildAppBar(context, statusBarHeight),
          Text('test')
        ],
      ));
}

The _buildAppBar method returns a SliverAppBar.

I need to use a Padding widget instead of the text, but I think that it will be like the same, that's the same issue.

Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87
Joseph Arriaza
  • 12,014
  • 21
  • 44
  • 63

3 Answers3

30

I found a better way to use non-slivers inside a CustomScrollView, use SliverToBoxAdapter widget. Give your non-sliver widget as child of SliverToBoxAdapter widget and your work done.

return Scaffold(
  body: CustomScrollView(
    slivers: <Widget>[
      SliverToBoxAdapter(
        child: Stack(
          children: <Widget>[
            Container(
              height: 200,
              width: 200,
              color: Colors.green,
            ),
            Positioned(
              child: Container(color: Colors.yellow),
              top: 50,
              left: 50,
            )
          ],
        ),
      )
    ],
  ),
);

this is the output of the above code

Dhanraj Verma
  • 647
  • 1
  • 9
  • 14
4

The best answer is not correct, it causes assertion padding == null. @blaneyneil wrote the right solution: use to SliverToBoxAdapter.

Dmitriy Blokhin
  • 574
  • 1
  • 6
  • 14
-6

Once you are working with slivers, you need to use a sliver child wrapping your other non-sliver widgets. Since you want to use Padding, you can actually take advantage of the SliverPadding widget, which accepts your Text as its child.

So, instead of having Text('test') as you have, replace it by SliverPadding(child: Text('test)) instead.

There are a few sliver widgets that you may want to be aware of. Take a look here at Collin Jackson's accepted answer and also at Slivers, Demystified article for better understanding.

Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87
  • 4
    There is no such field `child` in `SliverPadding`. It can only be used to wrap another sliver. Use `SliverToBoxAdapter` instead. – Panduka Nandara Apr 26 '20 at 18:19