【发布时间】:2020-08-13 13:13:29
【问题描述】:
我想在单击按钮时在 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() 中,它也不起作用。
非常感谢您的帮助。
【问题讨论】:
标签: android flutter dart mobile