Add Null Safety In Your Flutter App | 2022

Add Null Safety In Your Flutter App | 2022

In simple words by Ankit Kumar

Are you looking to add null safety to your Flutter projects?

Null safety can help you avoid common runtime errors and make your code more predictable. Here's how to get started:

  1. Update your Flutter and Dart versions: Null safety is available in Flutter 2.0 and Dart 2.12 and above versions. Make sure you have the latest version installed.

     dart --version // check current installed dart version
    
     dart pub upgrade --null-safety // update dart version
    
     dart pub get
    

    2. Run the below commands to know what libraries in your project needs to be upgraded to the latest null safety:

     dart pub outdated --model=null-safety
    

    3. Finally, run dart migration command which performs null safety migration on existing projects.

     dart migrate
    

    4. Now you can use '?' to mark variables and parameters as nullable. For example, 'String? name' means that the 'name' variable can be either a 'String' or 'null' .

    5. Use the '!' operator to mark the variables and parameters as non-nullable variables. For example, 'String! name' means that the 'name' variable must always be a 'String', and cannot be 'null'.

    6. Use the '??' operator to provide a default value for nullable variables. For example, 'name ??= 'Default Name' will assign the value 'Default Name' to 'name' if is 'null', and leave it unchanged if it is not 'null'.

    By following these steps, you can add null safety to your Flutter projects and make your code more predictable and reliable.

    Happy coding!