在设置不同的内容高度时,调整动画容器的大小时出现问题。
调整大小时会引发异常:
rendering渲染库捕获到异常════════
在布局期间引发了以下断言:
RenderFlex在底部溢出154个像素。
这是一个重现该问题的最小示例(在我的实际应用中,这个问题要复杂得多,但你明白了):
bool expanded;
initState() {
super.initState();
expanded = false;
}
void _toggleMode() {
setState(() {
expanded = !expanded;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Test")),
body: AnimatedContainer(
height: expanded ? 230 : 70,
duration: Duration(milliseconds: 800),
child: Column(
children: <Widget>[
Expanded(
child: PageView.builder(
itemBuilder: (context, position) {
return expanded
? Column(
children: <Widget>[
Container(height: 40, color: Colors.blue),
Container(height: 40, color: Colors.blue[400]),
Container(height: 40, color: Colors.blue[300]),
Container(height: 40, color: Colors.blue[200]),
Container(height: 40, color: Colors.blue[100]),
],
)
: Column(
children: <Widget>[
Container(height: 40, color: Colors.blue),
],
);
},
),
),
InkWell(onTap: _toggleMode, child: expanded ? Icon(Icons.keyboard_arrow_up) : Icon(Icons.keyboard_arrow_down))
],
),
),
);
}
在两种模式下(扩展与否),内容都适合容器(无溢出),问题仅在调整大小时出现。
当然,没有动画的基本容器不会发生问题。
我该如何处理?
发生这种情况的原因是您检查了扩展容器,然后在容器达到其最终大小之前立即将其退还
一种解决方法是使用带有NeverScrollableScrollPhysics()
编辑:您甚至不需要检查扩展,您将获得正确的动画
bool expanded;
initState() {
super.initState();
expanded = false;
}
void _toggleMode() {
setState(() {
expanded = !expanded;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Test")),
body: AnimatedContainer(
height: expanded ? 230 : 70,
duration: Duration(milliseconds: 800),
child: Column(
children: <Widget>[
Expanded(
child: PageView.builder(
itemBuilder: (context, position) {
return ListView(
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
Column(
children: <Widget>[
Container(height: 40, color: Colors.blue),
Container(height: 40, color: Colors.blue[400]),
Container(height: 40, color: Colors.blue[300]),
Container(height: 40, color: Colors.blue[200]),
Container(height: 40, color: Colors.blue[100]),
],
),
],
);
// : Column(
// children: <Widget>[
// Container(height: 40, color: Colors.blue),
// ],
// );
},
),
),
InkWell(onTap: _toggleMode, child: expanded ? Icon(Icons.keyboard_arrow_up) : Icon(Icons.keyboard_arrow_down))
],
),
),
);
}
谢谢,很好的把戏!正如您所说的,这是一种解决方法,但确实可以。实际上,我不是只有2个状态(是否扩展),而是具有不同高度的多个内容,因此我不得不将switch / case提取到一个函数中,然后按照您的建议用不可滚动的scrollable:D包装它。我用a
SingleChildScrollView
代替了ListView
,我猜可能会比较少(?)。奇迹般有效。您有主意:),感谢您的好评。