I already used a stateful widget, but it seems that the item wont display when pressing add.
final TextEditingController _commentController = TextEditingController();
List<String> _genComments = [
'comment 1',
'comment 2',
'comment 3',
'comment 4',
'comment 5'
];
Here’s my code in a ListView
where the items are displayed:
Expanded(
child: Container(
width: double.infinity,
child: ListView.builder(
itemCount: _genComments.length,
itemBuilder: (context, index) {
return Container(
width: double.infinity,
height: 100,
child: Card(
color: Colors.white,
elevation: 5,
child: Text(_genComments[index]),
),
);
},
),
),
),
Here’s my code in button where I use setState
:
child: ElevatedButton(
onPressed: () {
setState(() {
_genComments.add(_commentController.text);
});
_commentController.clear();
},
2
Answers
You can use this code to get add a new element in listview
when you call
setState
it will call thebuild
mehtod. which means all widget inside this mehtod will re-executed.common mistake is, people declare their variable inside
build
method. and this cause the state variable will not updated. because everytime they callsetState
the value is re-declared to initial value.example:
declare the state variable outside
build
method.so, when you call the
setState
will update the value to the variable.