'Add new Widget when button is clicked
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 .
Solution 1:[1]
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('');
});
}
),
],
);
}
Solution 2:[2]
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
Solution 3:[3]
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.
Solution 4:[4]
List<Widget> widgets = [];
Column(children: [
Expanded(
child: ListView.builder(
itemCount: widgets.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return widgets[index];
},
),
),
TextButton(
onPressed: () {
setState(() {
widgets.add(const Text("New Widget"));
});
},
child: const Text("add Widget"))
]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PaulHuang |
| Solution 2 | Xoltawn |
| Solution 3 | Manikandan R S |
| Solution 4 | avseng |
