What is Null Safety In Dart

What is Null Safety In Dart?

Null Safety is available in the Flutter beta channel, starting with build 1.24.0-10.2.pre. You can now migrate your flutter packages to use non-nullable types. so in this article, we will walk through What is Null Safety In Dart?

What is Null Safety In Dart?

  • Null Safety/Non-nullable
  • The null safety / non-nullable (by default), short NNBD, feature can currently be found at nullsafety.dartpad.dev.
  • Keep in mind that you can read the full spec here and the full roadmap here. Now, sound null safety has also been officially announced for Dart.

What does non-nullable by default mean?

void main() {
  String word;
  print(word); // illegal

  word = 'Hello, ';
  print(word); // legal
}

As you can see above, a variable being non-nullable by default means that every variable that is declared normally cannot be null. Consequently, any operation accessing the variable before it has been assigned is illegal.
Additionally, assigning null to a non-nullable variable is also not allowed:

void main() {
  String word;
  
  word = null; // forbidden
  world = 'World!'; // allowed
}
    • How does this help me?

      If a variable is non-nullable, you can be sure that it is never null. Because of that, you never need to check it beforehand.

      int? number = 4;
      void main() {
       if (number == null) return; // redundant
       int sum = number! + 2; // allowed because number is also non-nullable
      }
      
    • Remember

      • Instance fields in classes must be initialized if they are not nullable:
        class Foo {
          String word; // forbidden
        
          String sentence = 'Hello, World!'; // allowed
        }
      • Nullable types

        • You can use nullable types by appending a question mark? to a variable type:
          class Foo {
            String word; // forbidden
          
            String? sentence; // allowed
          }

 

  • A nullable variable does not need to be initialized before it can be used.

It is initialized as null by default:

 

void main() {
  String? word;
  
  print(word); // prints null
}
  • Power of   !

    • Appending ! to any variable e will throw a runtime error if e is null and otherwise convert it to a non-nullable value v.
      void main() {
        int? e = 5;
        int v = e!; // v is non-nullable; would throw an error if e were null
      
        String? word;
        print(word!); // throws runtime error if word is null
      
        print(null!); // throws runtime error
      }
  • late

    • The keyword late can be used to mark variables that will be initialized later, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable instance fields that are initialized later:
      class ExampleState extends State {
        late final String word; // non-nullable
      
        @override
        void initState() {
          super.initState();
      
          // print(word) here would throw a runtime error
          word = 'Hello';
        }
      }

      Accessing a word before it is initialized will throw a runtime error.

  • late final

    Final variables can now also be marked late:

    late final int x = heavyComputation();

    Here heavy computation will only be called once x is accessed. Additionally, you can also declare a late final without an initializer, which is the same as having just a late variable, but it can only be assigned once.

    late final int x;
    // w/e
    x = 5; // allowed
    x = 6; // forbidden
  • Note that all top-level or static variables with an initializer will now be evaluated late, no matter if they are final.
  • required

Formerly an annotation (@required), now built-in as a modifier. It allows to mark any named parameter for functions or classes as required, which makes them non-nullable:

void allowed({required String word}) => null;

This also means that if a parameter should be non-nullable, it needs to be marked as required or have a default value:

void allowed({String word = 'World'}) => null;

void forbidden({int x}) // compile-time error because x can be null (unassigned)
    =>
    null;

Any other named parameter has to be nullable:

void baz({int? x}) => null;
  • ?[]

    • The null aware?The [] operator was added for the index operator []:
      void main() {
        List<int>? list = [1, 2, 3];
      
        int? x = list?[0]; // 1
      }
  • ?..

    The cascade operator now also has a new null aware operator: ?…It causes the following cascade operations to only be executed if the recipient is not null. Therefore, the ?.. has to be the first cascade operator in a cascade sequence:

    void main() {
      Path? path;
    
      // Will not do anything if path is null.
      path
        ?..moveTo(3, 4)
        ..lineTo(4, 3);
    
      // This is a noop.
      (null as List)
        ?..add(4)
        ..add(2)
        ..add(0);
    }
  • Never

    Never is going to be a type like the previously existing Null (not null) defined in dart:core. Both of these classes cannot be extended, implemented, or mixed in. So that they are not intended to be used.

    Essentially, Never means that no type is allowed. Apart from that, You cannot instantiate Never. Nothing but Never in a List<Never> satisfies the generic type constraint of the list, which means that it has to be empty. List<Null>, however, can contain null:

    // Only valid state: []
    final neverList = <Never>[
      // Any value but Never here will be an error.
      5, // error
      null, // error
    
      Never, // not a value (compile-time error)
    ];
    
    // Can contain null: [null]
    final nullList = <Null>[
      // Any value but Null will be an error.
      5, // error
      null, // allowed
    
      Never, // not a value (compile-time error)
      Null, // not a value (compile-time error)
    ];

    For example, the compiler will infer List<Never> for an empty const List<T>.
    By programmers. Programmers don’t use Never

Conclusion:

So in this article, we have been through What is Null Safety In Dart.

Keep Learning !!! Keep Fluttering !!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields