'How to not delete last element in array (Dart language)
How to not delete last element in array list? Since if user keep clicking on remove button, it will return to negative value if there is no element in it.
Row(
children: [
Column(
children: [
TextButton(child: const Text ('Click Me'),
onPressed: () {
setState((){
_listTexts.add(textController.text);
});
}),
],
),
Column(
children: [
TextButton(child: const Text ('Remove Me'),
onPressed: () {
setState((){
_listTexts.removeLast();
});
}),
])
],
),
Solution 1:[1]
Simply check the length of the list before removing the element. If it reaches 1 item, it stops deleting.
Column(
children: [
TextButton(child: const Text ('Remove Me'),
onPressed: () {
if(_listTexts.length > 1) setState((){
_listTexts.removeLast();
});
}),
])
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 | Huthaifa Muayyad |
