gpt4 book ai didi

android - Flutter-单击按钮时在GridView中添加容器(窗口小部件)?

转载 作者:行者123 更新时间:2023-12-03 02:55:22 25 4
gpt4 key购买 nike

我想在单击按钮时在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()中,它也无法正常工作。

我将衷心感谢您的帮助。

最佳答案

这有效...

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]),
),
),
);
}
}

输出:

enter image description here

关于android - Flutter-单击按钮时在GridView中添加容器(窗口小部件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61501961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com