23

I created a model class, this is one of my a variable in model class

Datetime hotel_effect_open_date

but JSON response hotel_effect_open_date is null, getting an error in my application. and I modified to DateTime to String, it's working. In API created in the .net core, it looks like this,

Nullable<DateTime> hotel_effect_open_date

How to create a nullable variable in DART language?

3 Answers3

32

Now Dart is in the process of redesigning its type system. So that expression of that type can be either nullable or non-nullable. Something like this:
type? variable; // variable can be null.
Example:

int? a; // a can now be null.

Reference: Dart nullability syntax decision

AndiDog
  • 68,631
  • 21
  • 159
  • 205
Md Azharuddin
  • 1,346
  • 1
  • 9
  • 30
9

TLDR:

int? aNullableInt = null;

Detailed explanation:

Dart 2... and above

documentation: https://dart.dev/null-safety

With null safety, all of the variables in the following code are non-nullable:

// In null-safe Dart, none of these can ever be null.

var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();

To indicate that a variable might have the value null, just add ? to its type declaration:

int? aNullableInt = null;

Dart <2

DateTime example;
example = null;

Uninitialized variables have an initial value of null. Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.

int lineCount;
assert(lineCount == null);
Durdu
  • 4,649
  • 2
  • 27
  • 47
  • This is the older way to create null. The new (Flutter 2) way is something like: `int? lineCount;` Now lineCount can be an int or be null. – marty331 Jun 07 '21 at 13:55
0

you can create nullable variable like this for example:

int? a;
a = 4

sometimes you want to use type inference to be nullable, for example:

/// here a is of type int
var a = 1;
/// here b type is int?
var b = 1.nullable

extension<T extends Object> on T {
  T? get nullable => this;
}
Hosam Hasan
  • 564
  • 4
  • 11