Home > Net >  How do I make a button that adds a container with specific info inside in flutter
How do I make a button that adds a container with specific info inside in flutter

Time:09-26

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:

  1. Create a list:
List<Widget> widgets = [
  widget1,
  widget2,
],
  1. Change the ListView's children to widgets:
ListView(
  children: widgets,
),
  1. 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.

  • Related