这个错误通常出现在使用 const 构造函数时,尝试将一个空值(null)赋给一个字符串类型的参数。这是因为 const 构造函数要求所有参数都是常量,而 null 不是常量。

要解决这个问题,需要将参数类型从 String 改为 String?,这样就可以接受空值了。另外,也可以考虑使用非 const 构造函数,这样就可以接受任何类型的值了。

例如:

class Person {
  final String? name;
  final int age;

  Person({this.name, required this.age});
}

// 使用
Person person = Person(name: null, age: 20);
怎么解决A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor.

原文地址: https://www.cveoy.top/t/topic/cZG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录