如何在SingleChildScrollView中使用Expanded?

时间:2019-05-27 12:22:58

标签: flutter

如何在SingleChildScrollView中使用Expanded?我有Image.network,ListView.builder和Row(TextFormField和Icon按钮)的屏幕。我用Expanded包装ListView。如何用SingleChildScrollView包装此列?打开滑水板时,我需要移动屏幕才能看到我写的东西。当我换行时,会出现此错误。

      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: GestureDetector(
                child:
                Image.network(
                  postOne.imageUrl,
                  fit: BoxFit.fitWidth,
                  height: MediaQuery
                      .of(context)
                      .size
                      .width,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                ),
                onLongPress: () {},
                onDoubleTap: () {},
              ),
            ),
            Expanded(
              //height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                  itemBuilder: (context, position) {
                    return GestureDetector(
                        onLongPress: () {},
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(5.0),
                            child: new CheckboxListTile(
                                title: new Text(commentList
                                    .elementAt(position)
                                    .coment,
                                  style: TextStyle(fontSize: 18.0),),
                                value: values[commentList
                                    .elementAt(position)
                                    .coment],
                                onChanged: (bool value) {}),
                          ),
                        )
                    );
                  }
              ),
            ),
            Container(
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    new Flexible(
                      child: Theme(
                        data: new ThemeData(
                            brightness: Brightness.light,
                            primarySwatch: Colors.grey,
                            inputDecorationTheme: new InputDecorationTheme(
                              labelStyle: new TextStyle(
                                  color: Colors.black45, fontSize: 18.0
                              ),
                            )
                        ),
                        child: new Form(
                          key: _formKey,
                          child: new TextFormField(
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter the comment';
                              }
                            },
                            controller: commentController,
                            decoration: new InputDecoration(
                              labelText: "Add comment",
                              //hintText: 'Add comment'
                            ),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                    ),
                    new Container(
                        margin: EdgeInsets.only(left: 10.0, top: 12.0),
                        child: new IconButton(
                            icon: new Icon(Icons.send, color: Colors.black,),
                            onPressed: () {}
                        )
                    ),
                  ]),
            ),
          ],
        ),
      ),
I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816):   RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816):   _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816):   creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   RepaintBoundary ← ⋯
I/flutter ( 6816):   parentData: <none> (can use size)
I/flutter ( 6816):   constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816):   size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816):   http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816): 

screen

6 个答案:

答案 0 :(得分:53)

与使用SingleChildScrollViewCustomScrollView相比,使用SliverFillRemaining更容易。

尝试一下:

CustomScrollView(
  slivers: [
    SliverFillRemaining(
      hasScrollBody: false,
      child: Column(
        children: <Widget>[
          const Text('Header'),
          Expanded(child: Container(color: Colors.red)),
          const Text('Footer'),
        ],
      ),
    ),
  ],
)

答案 1 :(得分:6)

只需将SingleChildScrollView包裹在CenterAlign元素中即可。

示例:

  Align(
    alignment: Alignment.topCenter,
    child: SingleChildScrollView(
      child: Column(
        children: <Widget>[
          ...
        ]
      }
    }
  }

  Center(
    child: SingleChildScrollView(
      child: Column(
        children: <Widget>[
          ...
        ]
      }
    }
  }

答案 2 :(得分:1)

我尝试了Vijaya Ragavan解决方案,但对此做了一些调整,但仍然可以使用。 若要将Expanded与SingleChildScrollView一起使用,我使用了ConstrainedBox并将其高度设置为屏幕的高度(使用MediaQuery)。您只需要确保放入ConstrainedBox内的屏幕内容不大于屏幕的高度即可。

否则,将ConstrainedBox的高度设置为要在屏幕上显示的内容的高度。

SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    child: Text('Hello World!'),
                  ),
                ],
             ),
           )
 )

编辑: 要减去App​​Bar和/或状态栏的高度,请参见下文:

double screenHeightMinusAppBarMinusStatusBar = MediaQuery.of(context).size.height - appBar.preferredSize.height - MediaQuery.of(context).padding.top

答案 3 :(得分:0)

答案在于错误本身。当列位于具有滚动功能的视图中时,该列将尝试收缩包装其内容,但是由于您使用Expanded作为该列的子级,因此它正与尝试收缩包装其子级的列相反。这是导致此错误的原因,因为这两个指令彼此完全相反。

如错误日志中所述,请尝试以下操作:

考虑将mainAxisSize设置为MainAxisSize.min(用于列)并使用  FlexFit.loose适合于弹性(使用弹性而不是扩展)。

答案 4 :(得分:0)

正如已经指出的那样,因为您使用的是可滚动的滚动条,所以无法扩展到无穷大(从理论上讲,它们是无穷大的),这就是您尝试扩展ListView时发生的情况嵌套在SingleChildScrollView中。

您可以尝试使用NestedScrollView,或者,如果它符合您的要求并且已注释掉以下行,则可以尝试使用:

//height: MediaQuery.of(context).size.width*0.33,

例如,您可以将ListView包裹在具有该高度的ConstrainedBox(甚至只是普通的Container)中,而不是Expanded,就像这样:

 Container(
         height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                ...
               )
          )

由于您已经处于可滚动状态,因此较小的屏幕不会出现问题,因为整个树都是可滚动的。

答案 5 :(得分:0)

尝试一下

LayoutBuilder(
  builder: (context, constraint) {
    return SingleChildScrollView(
      child: ConstrainedBox(
        constraints: BoxConstraints(minHeight: constraint.maxHeight),
        child: IntrinsicHeight(
          child: Column(
            children: <Widget>[
              Text("Header"),
              Expanded(
                child: Container(
                  color: Colors.red,
                ),
              ),
              Text("Footer"),
            ],
          ),
        ),
      ),
    );
  },
)

遇到相同情况时,我从git问题获得了此解决方案。我没有git链接。我认为这可能对您有帮助。