How to not delete last element in array (Dart language)

Viewed 145

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();
              });
              }),
            ])
        ],
      ),
1 Answers

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();
     });
   }),
 ])
Related