如何在CustomScrollView中使用非Sliver小部件

11
我试图将一个文本小部件添加到CustomScrollView中,但我遇到了一些问题,比如目标不同的问题。
这是我的小部件:

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')
        ],
      ));
}

_buildAppBar方法返回一个SliverAppBar。

我需要使用Padding小部件替换文本,但我认为它会像原来的一样,这是相同的问题。


4
SliverToBoxAdapter 的翻译是“将盒子适配器转换为白银条”。 - blaneyneil
3个回答

30

我发现在CustomScrollView内使用非Sliver控件的更好方法是使用SliverToBoxAdapter小部件。将您的非Sliver控件作为SliverToBoxAdapter小部件的子级,然后就完成了。

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,
            )
          ],
        ),
      )
    ],
  ),
);

上面代码的输出


5
最佳答案并不正确,它会导致断言错误padding == null。 @blaneyneil 给出了正确的解决方案:使用SliverToBoxAdapter。

-6

一旦您开始使用slivers,您需要使用一个sliver child来包装其他非sliver小部件。由于您想使用Padding,您实际上可以利用SliverPadding小部件,它接受您的Text作为其子项。

因此,不要像您现在这样拥有Text('test'),而是将其替换为SliverPadding(child: Text('test))

还有一些sliver小部件可能会让您感兴趣。请查看Collin Jackson的被接受答案here,以及Slivers, Demystified文章,以便更好地理解。


4
SliverPadding 中不存在 child 字段。它只能用来包裹另一个 sliver。请改用 SliverToBoxAdapter - Panduka Nandara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接