How to handle NULL SAFETY in model classes?

1,326

Try to change like below.
(And you'd better change snake case variable name to 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});
}
Share:
1,326
PeakGen
Author by

PeakGen

CTO

Updated on January 01, 2023

Comments

  • PeakGen
    PeakGen over 1 year

    I am building the model classes of my Flutter application. I have built many flutter apps before but this is the first time I am engaging with the Flutter 2.0. My class is like below.

    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})
    }
    

    However I am getting errors for every parameter, just like below.

    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}
    

    I know i can add the required tag and more forward. But in most of the time these data will be pulled from the database, so I can't say exactly which one is null. However from the database side only the first_name and email are defined as not-null fields.

    What should I do here?

    • Alex Domenici
      Alex Domenici over 2 years
      Set the nullable fields by adding a question mark after their type. For example: String? last_name;