首页 > 解决方案 > 在 SingleChildScrollView 中实现嵌套的 ListView

问题描述

在这个示例代码中,我想嵌套ListView在里面SingleChildScrollView,但是我得到了这个错误:

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

我的代码:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'test',
      home: Scaffold(
        appBar: AppBar(
          title: Text("Scrollview Demo"),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                height: 50.0,
                color: Colors.green,
                child: Center(
                  child: Text('message'),
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: 30,
                  itemBuilder: (context, index) {
                    return ListTile(title: Text("Index : $index"));
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

标签: flutterflutter-layout

解决方案


在 ListView 中,您可以设置

收缩包装:真

这样 ListView 只占用它需要的空间。

要禁用 ListView 上的滚动,以便它使用 SingleChildScrollView 的滚动,您可以设置

物理:NeverScrollableScrollPhysics()。

如果这里是无限的,您需要删除将孩子设置为可用屏幕的 Expanded。

这里:

SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            height: 50.0,
            color: Colors.green,
            child: Center(
              child: Text('message'),
            ),
          ),
          Flexible(
            child: ListView.builder(
              itemCount: 30,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return ListTile(title: Text("Index : $index"));
              },
            ),
          ),
        ],
      ),
    )

推荐阅读