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;
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者