Hello I'm still learning but cant find it for some reason, My question is: I want to make a button that on press creates a new container and organizes it in a listview widget, how do I do that? do you have a tutorial or article about it that can help me?
CodePudding user response:
- Create a list:
List<Widget> widgets = [
widget1,
widget2,
],
- Change the
ListView
's children towidgets
:
ListView(
children: widgets,
),
- Make a button that when pressed creates a new
Container
:
TextButton(
onPressed: () {
widgets.add(Container(child: child));
},
child: Text("Create a new container"),
),
CodePudding user response:
You have to initialize list of type Widget
List<Widget> widget=<Widget>[];
On Button Tap call the following method:
void addContainer(){
setState(() {
widgetList.add(Padding(
padding: const EdgeInsets.all(8.0),
child: Container(height: 20,width: 30,color: Colors.red,),
));
});
}
Add Following code for create your list:
ListView.builder(
itemCount: widgetList.length,
itemBuilder: (BuildContext context, int index) {
return
widgetList.isNotEmpty?
widgetList.elementAt(index):SizedBox();
},
),
CodePudding user response:
Without example I would say the easier way would be to have an array with the widget you want in your listview, then on click add an element in your list with setState.
List<Widget> views = [Text("test"), Text("test2")];
then
ListView(children: views)
and final a function to call with your button
void addContainer()
{
setState((){
views.add(Container(color: Colors.red));
});
}
I did not try it so it might contain some typos, but you get the logic.