关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

error • The parameter ‘name‘ can‘t have a value of ‘null‘ because of its type错误

发布时间:2023-06-26 17:00:12

问题描述

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;

   



/template/Home/leiyu/PC/Static