在按下按钮时动态添加一个小部件

dynamically add a widget on press of button

我创建了一个 class,其中有一个小部件,我希望它在按下按钮时多次出现在主页上。

https://gyazo.com/f9cc3e2c1f48e9efeb7b1d1c9b0b988e

正如您在这张图片中看到的那样,'home care kit' 矩形是小部件,我希望它们在您按下添加设备按钮时出现。

按钮代码如下:

child: RaisedButton(

elevation: 0,
shape: RoundedRectangleBorder(
  borderRadius: BorderRadius.circular(40.0),
side: BorderSide(color: Colors.transparent)),
onPressed: () {print('Clicked!');},
color: Colors.transparent,
textColor: Colors.white,
child: Text('Add Device', style: TextStyle(color: Colors.white, fontSize: 18)),

),

并且小部件 class 简称为 HomeCareKit()

您首先需要一个小部件列表:

List<Widget> _widgetList = [];

然后您将此小部件列表传递给您的 ListViewColumn,例如:

ListView(
    children:_widgetList,
  )

要动态添加小部件,您可以在 onPressed:

中执行此操作
setState(() {
  _widgetList.add(HomeCareKit());
});