【问题标题】:How to handle NULL SAFETY in model classes?如何处理模型类中的 NULL SAFETY?
【发布时间】:2021-11-01 17:52:45
【问题描述】:

我正在构建我的 Flutter 应用程序的模型类。我之前构建过很多 Flutter 应用,但这是我第一次接触 Flutter 2.0。我的课如下。

import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class User {
  int iduser;
  String uid;
  String first_name;
  String last_name;
  String profile_picture;
  String email;
  String phone;
  bool is_disabled;
  int created_date;
  int last_updated;

  User({this.iduser,
  this.uid,
  this.first_name,
  this.last_name,
  this.profile_picture,
  this.email,
  this.is_disabled,
  this.created_date,
  this.last_updated})
}

但是,每个参数都出现错误,如下所示。

The parameter 'iduser' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.dart(missing_default_value_for_parameter)
{int iduser}

我知道我可以添加required 标签和更多转发。但在大多数情况下,这些数据会从数据库中提取出来,所以我不能确切地说哪一个是空的。然而,从数据库方面来看,只有 first_nameemail 被定义为 not-null 字段。

我应该在这里做什么?

【问题讨论】:

  • 通过在类型后添加问号来设置可为空的字段。例如:字符串?姓氏;

标签: android ios flutter dart dart-null-safety


【解决方案1】:

尝试如下更改。
(而且你最好将蛇案例变量名称更改为 lowerCamelCase) https://dart.dev/guides/language/effective-dart/style#do-name-other-identifiers-using-lowercamelcase

class User {
  int? iduser;
  String? uid;
  String? first_name;
  String? last_name;
  String? profile_picture;
  String? email;
  String? phone;
  bool? is_disabled;
  int? created_date;
  int? last_updated;

  User(
      {this.iduser,
      this.uid,
      this.first_name,
      this.last_name,
      this.profile_picture,
      this.email,
      this.is_disabled,
      this.created_date,
      this.last_updated});
}

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2020-12-22
    • 1970-01-01
    • 2021-06-22
    • 2021-04-13
    相关资源
    最近更新 更多