问题描述
error • The parameter 'name' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib\models\chat_model.dart:7:19 • (missing_default_value_for_parameter)
error • The parameter 'message' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib\models\chat_model.dart:7:30 • (missing_default_value_for_parameter)
error • The parameter 'time' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib\models\chat_model.dart:7:44 • (missing_default_value_for_parameter)
error • The parameter 'avatarUrl' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib\models\chat_model.dart:7:55 • (missing_default_value_for_parameter)
如图:
报错的代码:
class ChatModel {
final String name;
final String message;
final String time;
final String avatarUrl;
ChatModel({this.name, this.message, this.time, this.avatarUrl});
}
报错是说参数不能为null,但是可能存在隐形的赋值为null的可能。代码修改成如下
class ChatModel {
final String? name;
final String? message;
final String? time;
final String? avatarUrl;
ChatModel({this.name, this.message, this.time, this.avatarUrl});
}
改成这样后会报其的错误:
error • The argument type 'String?' can't be assigned to the parameter type 'String' at lib\pages\chat_screen.dart:25:53 • (argument_type_not_assignable)
error • The argument type 'String?' can't be assigned to the parameter type 'String' at lib\pages\chat_screen.dart:31:23 • (argument_type_not_assignable)
error • The argument type 'String?' can't be assigned to the parameter type 'String' at lib\pages\chat_screen.dart:35:23 • (argument_type_not_assignable)
error • The argument type 'String?' can't be assigned to the parameter type 'String' at lib\pages\chat_screen.dart:43:21 • (argument_type_not_assignable)
原因分析
报错是说参数不能为null,但是可能存在隐形的赋值为null的可能。这些参数都是在构造函数中调用。说明这些参数是必须的就可以了。
解决措施
构造函数添加required。代码如下:
class ChatModel {
final String name;
final String message;
final String time;
final String avatarUrl;
ChatModel({required this.name, required this.message,required this.time, required this.avatarUrl});
}
另外最新的Dart 强制null safety。定义一个变量时暂时没有赋值,记得加上late告知Dart 这个变量稍后会赋值。不然会报“Non-nullable instance field 'controller' must be initialized” 错误。 eg
late CameraController controller;