简体   繁体   中英

How to create nullable variable in Dart

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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