我有一个容器列表,我想为容器设置动画。
例如,更改他的身高/宽度,并更改容器的内容。
到目前为止,我所做的是:
containerHeight = MediaQuery.of(context).size.height * 0.20;
body: Container(
child: ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
color: Colors.black,
height: containerHeight,
child: IconButton(
icon: Icon(Icons.list),
color: Colors.white,
onPressed: () {
setState(() {
containerHeight = MediaQuery.of(context).size.height * 0.35;
});
},
),
),
);
},
),
我打算使用AnimatedContainer
,但是即使现在还没使用它,如果我按一下按钮,什么也没发生
答案 0 :(得分:3)
这就是我如何使其工作的方式。我只是用动画容器替换了容器
class _HomePageState extends State<HomePage> {
List<String> dataList = ['Andrew', 'Test', 'Data', 'Random'];
double containerHeight;
bool expanded = false;
@override
Widget build(BuildContext context) {
containerHeight = expanded
? MediaQuery.of(context).size.height * 0.20
: MediaQuery.of(context).size.height * 0.30;
return Scaffold(
appBar: AppBar(
title: Text('Test App'),
),
body: ListView.builder(
itemCount: dataList.length,
itemBuilder: (context, index) {
return AnimatedContainer(
curve: Curves.easeOut,
duration: Duration(milliseconds: 400),
color: Colors.red,
height: containerHeight,
margin: EdgeInsets.all(8),
child: Center(
child: Text(
dataList.elementAt(index),
style: TextStyle(
color: Colors.white,
),
),
),
);
},
),
floatingActionButton: FloatingActionButton(onPressed: () {
setState(() {
expanded = !expanded;
});
}),
);
}
}
输出
编辑
如果只想折叠您正在点击的元素,那么最好创建一个可以容纳容器当前状态的类。
class DataModel {
String title;
bool expanded;
DataModel(this.title) {
expanded = false;
}
}
在此处,展开将跟踪容器的大小。
现在稍微重构前面的代码
class _HomePageState extends State<HomePage> {
// Initialize DATA MODEL list with some random values.
List<DataModel> dataList = ['Andrew', 'Test', 'Data', 'Random']
.map<DataModel>((s) => DataModel(s))
.toList();
double containerHeight;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test App'),
),
body: ListView.builder(
itemCount: dataList.length,
itemBuilder: (context, index) {
DataModel item = dataList.elementAt(index);
// Check if the item is expanded or not and set size accordingly
containerHeight = item.expanded
? MediaQuery.of(context).size.height * 0.20
: MediaQuery.of(context).size.height * 0.30;
return GestureDetector(
onTap: (){
// On tap reverse the expanded state of the data which will resize
// the widget as setState is being called
setState(() {
item.expanded = !item.expanded;
});
},
child: AnimatedContainer(
curve: Curves.easeOut,
duration: Duration(milliseconds: 400),
color: Colors.red,
height: containerHeight,
margin: EdgeInsets.all(8),
child: Center(
child: Text(
dataList.elementAt(index).title,
style: TextStyle(
color: Colors.white,
),
),
),
),
);
},
),
);
}
}