简体   繁体   English

如何清理一个类的实例?

[英]How to clean up instances of a class?

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.我有一个 Student 类的列表,每次我按下一个按钮时,我都会将 Student 类的新实例添加到这个列表中。 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 _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.这张图片显示,当我点击按钮时,每一行都会增加一个类的实例,但我想应该发生的是总是只有一个类。

在此处输入图像描述

You can call the .clear() method on your list _studentsTest :您可以在列表_studentsTest上调用.clear()方法:

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

use _studentsTest.clear() before之前使用_studentsTest.clear()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM