Home > Mobile >  Add new Widget when button is clicked
Add new Widget when button is clicked

Time:03-18

I'm trying to make a button add a new widget when it's clicked.

To make it simple , I'm having this widget :

Column(
                              children: [
                                InputField(
                                  label: "Product",
                                  content: "Type product Name",
                                  fieldValidator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return "This input is required";
                                    }
                                    return null;
                                  },
                                ),

As you can see , I want a button that adds a new InputField inside this column. And if it's possible how can I make the button only appear at the end of the last item .

CodePudding user response:

Maybe you can use a list to control InputField data.

final List<String> inputs = [];

@override
Widget build(BuildContext context) {
  retrun Column(
          children: [
            ...inputs.map((input) => InputField(...))toList(),
            FlatButton(
              child: Text('click'),
              onPressed: () {
                setState(() {
                  inputs.add('');
                });
              }
            ),
          ],
        );
}

CodePudding user response:

You can define variable to hold a list of InputField and display them dynamically using :

Column(
    children: inputs.map((dynamic e) {
        return e;
    }).toList(),
)  

And then you can wrap in with a Column or ListView to display the button:

Column(
    children:[
        Column(
            children: inputs.map((dynamic e) {
                return e;
        }).toList(),
        _Button()
)
    ]
)  

Of course it is not the "best" solution, implementation depends on your needs

CodePudding user response:

Best use the listview builder to build the dynamic text view widgets

Map<TextEditingController, int> list = Map();

ListView.builder(
   itemCount: list.lenght,
   itemBuilder: (BuildContext context,int index){
   return TextFormField()
  }
)

Inside the list add TextEditingController so that you can get value from the textformfield.

or you can use the key for each widget to get the value from the widget.

  • Related