在此记录项目中所遇到问题及解决方案
在SingleChildScrollView中直接添加GridView或ListView,会报以下错误(Another exception was thrown: Vertical viewport was given unbounded height)。
Code:
SingleChildScrollView(
child: Column(
children: <Widget>[
Text('Cate'),
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5,
crossAxisSpacing: 15,
mainAxisSpacing: 0,
childAspectRatio: 0.6,
),
primary: false,
itemCount: 10,
itemBuilder: (context,index){
return Text('C');
}
),
],
),
)
这段代码发生错误的原因是GridView没办法获取到SingleChildScrollView的高度。
有两个方法解决:
- 使用SizedBox或Container来固定高度
SingleChildScrollView(
child: Column(
children: <Widget>[
Text('Cate'),
Container(
height: 100,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5,
crossAxisSpacing: 15,
mainAxisSpacing: 0,
childAspectRatio: 0.6,
),
primary: false,
itemCount: 10,
itemBuilder: (context,index){
return Text('C');
}
),
),
],
),
)
- 使用CustomScrollView+SliverGrid 或 SliverList
import 'package:flutter/material.dart';
class Test extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ListView"),
),
body: Container(
child: CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildListDelegate(
[
HeaderWidget("Header 1"),
HeaderWidget("Header 2"),
HeaderWidget("Header 3"),
HeaderWidget("Header 4"),
],
),
),
SliverList(
delegate: SliverChildListDelegate(
[
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
BodyWidget(Colors.green),
BodyWidget(Colors.orange),
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
],
),
),
SliverGrid(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
delegate: SliverChildListDelegate(
[
BodyWidget(Colors.blue),
BodyWidget(Colors.green),
BodyWidget(Colors.yellow),
BodyWidget(Colors.orange),
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
],
),
),
],
),
),
);