Home > database >  How to clean up instances of a class?
How to clean up instances of a class?

Time:12-23

I have a list of the Student class which every time I press a button I add new instances of the Student class to this List. However, every time I press the button, the classes are incrementing, when it should only go to the values that I selected. My question is, how can I clear all items from this List _studentsTest ?

 List<Student>? _studentsTest = []; //my class

//when I press the button I do this
onConfirm: (results) {
        setState(() {
          _studentsTest = results.cast<Student>();
        });
      }

This image shows that each line when I click on the button increments an instance of the class, but what I imagine should happen is that there will always be only one class.

enter image description here

CodePudding user response:

You can call the .clear() method on your list _studentsTest:

Removes all objects from this list; the length of the list becomes zero.

List<Student>? _studentsTest = [];
  
  onConfirm: (results) {
    _studentsTest.clear();
    setState(() {
      _studentsTest = results.cast<Student>();
    });
  }

CodePudding user response:

use _studentsTest.clear() before

     onConfirm: (results) {
        setState(() {
          _studentsTest.clear();
          _studentsTest = results.cast<Student>();
        });
      }
  • Related