Understanding Dart Null-Safety — Dart Programming — Part 7
Hello guys, we only have this stories to talk about Dart basic. And i want that story to talk about Null-Safety, which is big change in Flutter 2.0 and in Dart 2.12. Let’s FlutterWithMe!
Before Null-Safety, Object in Dart look like this.
And after update Null-Safety. Object will separate into two type.
And in Nullable Object, detail separate will be like
Which null-safety changes are:
- Types in your code are non-nullable by default <=> variables can’t cointain null unless you say they can.
- Runtime null errors turn into edit-time compile errors <=> fastest way to observe and fix issues.
- But the main point of Null-Safety isn’t eliminate the null from the equation:
- Null is still exist in every Dart Program
- Null highlights the “absence” of a value
- The issue is not null itself, but rather have null where you don’t expect.
- Goal of null-safety is to have control into where, how and when null can flow in your program.
- Types are made nullable by add them with question mark (?). Ex: String? , int?, List<int?>?.
- Will get compile error when access into props or method when using nullable type if you don’t check null.
- Non-void non-nullable function must always return the correct non-nullable type.
- Non-nullable class fields must be initialized before the constructor body.
- Non-nullable optional parameters must be initialized in the paremeters list.
- The “late” modifier lets you tell the analyzer that the variable is safe and give you lazy-initializated fields.
You can also combine late with final like this
// Using null safety:
class Coffee {
late final String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
With old code and dart versionm, you can migrate to null-safety with command following to this guide.
I think that’s sum-up i want to bring about which change in null-safety. Hope it’ll help you for a little bit. Thanks for spend your time!