【问题标题】:NoSuchMethodError. The method "add" was called on null even after initializing ListNoSuchMethodError。即使在初始化 List 之后,也会在 null 上调用方法“add”
【发布时间】:2021-04-04 14:28:00
【问题描述】:

我在 Flutter 中创建了一个 TextFormField。我有一个名为 ParticipantsData 的类,其中列出了一些属性。我可以通过在另一个名为“RegistrationForm”的类中创建 ParticipantsData 类的对象来访问和存储所有这些属性中的值。但是,即使在初始化它们之后,我也无法将数据存储在 List 类型的属性中。

我试过了:

 - List.filled() 
 - =[]
 - =[""]
 - List.generate()
 - List()
 - List<String>()
 - List<String>(length)

我已经多次更改我的代码并尝试了许多方法,但似乎没有任何效果。我在这里发帖不多,因为我通常会在 stackoverflow 上找到解决方案,但这次我什么也找不到。 无法发布整个代码,因为它太长了。下面是相关代码:

参与者数据类:

class ParticipantsData {
  List name = []; //members
  bool paymentstatus = false; //payment
  String email = ""; //email
  String address = ""; //address
  List contact = []; //contact
  String collegename = ""; //collegename
  String password = ""; //password
  String teamname = ""; //teamname
  var modules = List<String>(6); //modules

  ParticipantsData({
    this.name,
    this.email,
    this.contact,
    this.collegename,
    this.address,
    this.modules,
    this.password,
    this.paymentstatus,
    this.teamname,
  });
}

下面是Register类的相关代码:

class _RegistrationForm extends State<RegistrationForm> {
  final ParticipantsData data = new ParticipantsData();

//This is the onSaved method of a TextFormField, which is in a loop.
(String value) {                                         //Tried this...
                  data.name[i + 1] = value;
                  print('${data.name[i + 1]}');
                }),

(String value) {                                             //And this too...
                  data.name.add(value); 
                  print('${data.name[i + 1]}');
                }),

【问题讨论】:

    标签: list flutter nosuchmethoderror


    【解决方案1】:

    在构造函数中初始化时,分配的值变为空。如果您没有在构造函数中包含这些字段,它们将不会重置为 null。

    但是,如果在创建实例时未提供该字段,您可能希望在构造函数中分配值并需要一些默认值。这样做的方法如下:

    class MyClass {
    
      // Don't initialize here
      List x;
      int y;
      
      MyClass({
          this.x,
          this.y = 10, // If y is not assigned, it will take a default value of 10
      }) {
        // Constructor body
        this.x = this.x ?? []; // If x is not assigned, it will take a value of []
      }
    }
    

    注意 y 可以直接提供默认值,因为 10 是一个常量值。您只能在构造函数参数列表中分配常量默认值。由于 [ ] 不是常量表达式或值,因此不能直接将其赋值为默认值,因此您需要定义构造函数体分配 x = [ ] if x em> 为空。

    this.x = this.x ?? [];
    

    你可以用类似的方式初始化其他的。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2021-10-25
      • 2021-06-10
      相关资源
      最近更新 更多