Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
     });
   }),
 ])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading