我想在单击按钮时在GridView中添加一个容器小部件。我可以使用列窗口小部件来执行此操作,但不能使用GridView来完成此操作。
import 'package:flutter/material.dart';
List<Widget> gridChild = [
Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
),
Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
),
Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
),
Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
),
Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
),
];
class Grid extends StatefulWidget {
@override
_GridState createState() => _GridState();
}
class _GridState extends State<Grid> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.red,
child: Icon(Icons.add),
onPressed: () {
setState(() {
gridChild.add(Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
));
print(gridChild.length);
});
},
),
body: Container(
child: GridView.count(
crossAxisCount: 2,
children: gridChild,
),
),
);
}
}
我所做的是我在小部件列表中添加了一个容器。单击底部时,列表的长度增加,但是未在屏幕上添加容器。即使我将函数放在setState()中,它也无法正常工作。
非常感谢您的帮助。
答案 0 :(得分:2)
这有效...
class Grid extends StatefulWidget {
@override
_GridState createState() => _GridState();
}
class _GridState extends State<Grid> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.red,
child: Icon(Icons.add),
onPressed: () {
setState(() {
gridChild.add(Container(
margin: EdgeInsets.all(8.0),
width: 30.0,
height: 50.0,
color: Colors.green,
));
});
},
),
body: Container(
child: GridView.count(
crossAxisCount: 2,
children: List.generate(gridChild.length, (index) => gridChild[index]),
),
),
);
}
}
输出:
答案 1 :(得分:0)
在正文中使用 GridView.builder 。它应该可以解决您的问题。我真的不知道为什么,但是我知道它有效。希望有人可以更新此答案并提供解释。
GridView.builder(
itemCount: gridChild.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (BuildContext context, int index){
return gridChild[index];
},
),