简体   繁体   English

无法在 Flutter 中创建命名构造函数

[英]Cannot create named constructor in Flutter

I am new to Flutter.我是 Flutter 的新手。

I am creating a named constructor to work with flutter Models.我正在创建一个命名构造函数来处理颤振模型。 But for some reason it is showing an error:但由于某种原因,它显示了一个错误:

class ImageModel {
  int id;
  String url;
  String title;

  // constructor
  ImageModel(this.id, this.url, this.title);

  // named constructor
  ImageModel.fromJSON(Map<String, dynamic> parsedJson) { 
    id = parsedJson['id'];
    url = parsedJson['url'];
    title = parsedJson['title'];
  }
}

Error:错误:

Non-nullable instance field 'url' must be initialized.
Try adding an initializer expression, or add a field initializer 
in this constructor, or mark it 'late'.dartnot_initialized_non_nullable_instance_field

I read the documentation, and found this solution, not sure why this is required at this place.我阅读了文档,并找到了这个解决方案,但不确定为什么在这个地方需要这样做。 I know its use case, but should not this work without this ?我知道它的用例,但如果没有这个,它不应该工作吗?

class ImageModel {
  late int id; // refactor
  late String url; // refactor
  late String title; // refactor
.
.
.

You have used incorrect syntax for the named constructor.您对命名构造函数使用了不正确的语法。

Instead of代替

  ImageModel.fromJSON(Map<String, dynamic> parsedJson) { 
    id = parsedJson['id'];
    url = parsedJson['url'];
    title = parsedJson['title'];
  }

it must be一定是

ImageModel.fromJSON(Map<String, dynamic> parsedJson) :
    id = parsedJson['id'],
    url = parsedJson['url'],
    title = parsedJson['title'];

The object is initialized after colon(:) in named constructor and curly brackets({}) are then used if you want to perform some task after initialization of object.对象在命名构造函数中的冒号(:) 之后初始化,然后如果您想在对象初始化后执行某些任务,则使用大括号({})。 Since you directly used {} after named constructor, it created an empty object for you and hence all parameters were null which you were trying to initialize in the function body.由于您在命名构造函数之后直接使用了 {},因此它为您创建了一个空对象,因此您尝试在函数体中初始化的所有参数均为 null。 That's why this issue was solved after using 'late' keyword.这就是为什么在使用 'late' 关键字后解决了这个问题。

do you like this way你喜欢这种方式吗

factory ImageModel.fromJson(Map<String, dynamic> json) {
    return ImageModel(
      json["id"],
      json["url"],
      json["title"],
    );
  }

And i prefer我更喜欢

class ImageModel {
  int id;
  String url;
  String title;

  // constructor
  ImageModel({
    required this.id,
    required this.url,
    required this.title,
  });

  factory ImageModel.fromJson(Map<String, dynamic> json) {
    return ImageModel(
      id: json["id"],
      url: json["url"],
      title: json["title"],
    );
  }
}

The Dart compiler complains because of its "null safety" feature. Dart 编译器抱怨它的“空安全”特性。 This means, that variable types like int or String must be initialised.这意味着,必须初始化像intString这样的变量类型。 This is been checked for at compile time.这是在编译时检查的。 You can either add required in the constructor您可以在构造函数中添加required

  ImageModel({
    required this.id,
    required this.url,
    required this.title,
  });

so that you cannot call the constructor without initialising the fields or let the compiler know that you will take care of the initialisation later by adding the late keyword (as you did).这样你就不能在不初始化字段的情况下调用构造函数,或者让编译器知道你稍后会通过添加late关键字来处理初始化(就像你所做的那样)。 Of course you can also initialise the variables with some default values, if there are such当然你也可以用一些默认值初始化变量,如果有这样的

  int id = 0;
  String url = "https://www.example.com/default.jpg";
  String title = "Default Text";

but that seems to be more of a corner case.但这似乎更像是一个极端情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM