首先需要一个滚动页面
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Center(
child: Wrap(
children: <Widget>[
],
),
),
),
);
按照文档编写ListView和GridView
class Lists extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
ListTile(
title: Text(
"我是列表第一项",
style: TextStyle(color: Colors.red),
),
),
ListTile(
title: Text(
"我是列表第二项",
style: TextStyle(color: Colors.yellow),
),
),
ListTile(
title: Text(
"我是列表第三项",
style: TextStyle(color: Colors.blue),
),
)
],
);
}
}
class GridViews extends StatelessWidget {
List<Widget> _getList() {
List<Widget> list = new List();
for (var i = 0; i < 20; i++) {
list.add(Container(
alignment: Alignment.center,
color: Colors.blue.shade50,
child: Text(
"第${i + 1}条数据",
style: TextStyle(color: Colors.red, fontSize: 20),
),
));
}
return list;
}
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 5, //垂直间距
crossAxisSpacing: 10, //水平间距
padding: EdgeInsets.all(10),
childAspectRatio: 2, //宽高比例
children: _getList(),
);
}
}
把ListView和GridView引入页面
body: SingleChildScrollView(
child: Center(
child: Wrap(
children: <Widget>[
Lists(),
GridViews(),
],
),
),
),
保存,恭喜你,喜提报错
Cannot hit test a render box that has never been laid out.
当ListView、GridView作为Wrap、Column等组件的子组件时,若外部没有设置高度,则会产生此报错。
若需求高度能够自适应
解决放案:为ListView、GridView设置属性 shrinkWrap: true,
return GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 5, //垂直间距
crossAxisSpacing: 10, //水平间距
padding: EdgeInsets.all(10),
childAspectRatio: 2, //宽高比例
shrinkWrap: true,
children: _getList(),
);
刷新后,报错消失,但是发现其只可内部滚动。
若要使其更随外部页面整体滚动,为其设置属性:physics: NeverScrollableScrollPhysics(),
return GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 5, //垂直间距
crossAxisSpacing: 10, //水平间距
padding: EdgeInsets.all(10),
childAspectRatio: 2, //宽高比例
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: _getList(),
);
至此,需求达成。
参考https://www.jianshu.com/p/60abecfdc51d
网友评论