SingleChildScrollView内部的PageView.builder抖动

时间:2020-08-25 04:36:35

标签: flutter widget scrollview flutter-pageview

我正在尝试在SingleChildScrollView中使用PageView.builder,但我总是得到一个错误提示

RenderBox was not laid out: RenderRepaintBoundary#490ce relayoutBoundary=up15 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'

这是代码的一部分

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
            child: PageView.builder(
          itemCount: 3,
          scrollDirection: Axis.horizontal,
          reverse: false,
          itemBuilder: (BuildContext context, int index) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 4.0),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey,
                  borderRadius: BorderRadius.all(Radius.circular(4.0)),
                ),
              ),
            );
          },
        )
.....

我应该在代码中添加一些内容吗?

1 个答案:

答案 0 :(得分:1)

如果您希望PageView小部件的子级可滚动,则尝试用itemBuilder小部件包装SingleChildScrollView方法的根小部件并将其从当前位置移除。

因此代码如下:

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: PageView.builder(
          itemCount: 3,
          scrollDirection: Axis.horizontal,
          reverse: false,
          itemBuilder: (BuildContext context, int index) {
            return SingleChildScrollView( // Moving this widget down to this position is the only change in the code...
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 4.0),
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.grey,
                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                  ),
                ),
              ),
            );
          },
        ),
.....

问题是SingleChildScrollView小部件的高度是无限的,因为滚动功能和PageView小部件会尝试采用所有可用的高度,因此它试图将其设置为无限的高度,我认为这是是什么引起了问题。