在单击按钮时添加新的小部件,并带有返回小部件的功能 [英] Add New Widget on button click with a finction that returns a widget
问题描述
您好,我是Flutter的新手,我想知道是否可以通过单击按钮添加新的小部件.我调查了很多类似堆栈溢出的问题.但是由于我的知识不足,大多数问题对我来说似乎很复杂且难以掌握.我要做的就是在旧的构建容器下面添加一些容器
Hello i am new to Flutter and I want to know if there is a way to add new Widgets with a button click. I looked into many stack overflow similar Questions. but due to my poor knowledge most of them seems complex to me and hard to grasp. All i need to do is add some containers below old build containers
class MedPreC extends StatefulWidget {
@override
_MedPreCState createState() => _MedPreCState();
}
Widget returnWidget() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: double.infinity,
height: 40,
color: Colors.red,
),
);
}
class _MedPreCState extends State<MedPreC> {
var child2 = Column(
children: [
returnWidget(),
],
);
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Expanded(
child: Container(
color: Colors.yellow,
height: 400,
width: double.infinity,
child: child2,
),
),
RaisedButton(
child: Text("Add"),
onPressed: () {
setState(() {
//
child2.children.add(returnWidget());
//
});
},
)
],
),
);
}
}
这是我到目前为止编写的代码.整个代码将在另一个带有脚手架和填充物的类中调用returnWidget()返回一个红色的容器child2是一个在黄色容器内调用的列,其中一个红色容器作为其子容器之一我需要在按钮上添加更多的红色容器谢谢您了
This is the code i have made so far. This whole code will be called inside another class with scafold and stuffs returnWidget() Returns a red container child2 is a Column called inside a yellow Container with one red container as one of its children i need to add more redcontainers on button press Thank you thats all
推荐答案
尝试一下
class AddWidget extends StatefulWidget {
@override
_AddWidgetState createState() => _AddWidgetState();
}
class _AddWidgetState extends State<AddWidget> {
List<Widget> containerList = [];
Widget returnWidget() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: double.infinity,
height: 40,
color: Colors.red,
),
);
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Expanded(
child: Container(
color: Colors.yellow,
height: 400,
width: double.infinity,
child: Column(children: containerList),
),
),
RaisedButton(
child: Text("Add"),
onPressed: () {
setState(() {
containerList.add(returnWidget());
});
},
)
],
),
);
}
}
这篇关于在单击按钮时添加新的小部件,并带有返回小部件的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!