What is a Null safety in Flutter?

What is a Null safety in Flutter?

Null safety is a new major productivity feature that helps developers to avoid null exceptions. So, in this article, we will see what is a Null safety error in Flutter.

What is a Null safety error in Flutter?

Dart serves a special role in Flutter, providing developer features such as hot reload. It enables multi-platform apps for mobile, desktop, and web via Dart’s flexible compiler technology. Null safety is a feature that helps developers to avoid null exceptions, a class of bugs that are often hard to spot. This feature also enables a range of performance improvements.

Why null safety?

Dart is a type-safe language. This means that when you get a variable of some type, the compiler can guarantee that it is of that type. But type safety itself doesn’t guarantee that the variable is not null.
Null errors are very common. A search on GitHub leads to thousands of issues caused by unexpected nulls in Dart code. Also, there are thousands of commits trying to fix those issues. Let’s see if you can spot the nullability problems in the following Flutter app, imagining that Config and WeatherService are backend services used by the app:

class MyApp extends StatelessWidget
 {
  @override
  Widget build(BuildContext context) {
    final localizedAppName = Config.getAppName();
    final temperatures = WeatherService.getTemperatures();
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text(localizedAppName ?? "")),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text('Temperature next 5 days:'),
                for (final t in temperatures) Text(t.round().toString()),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class Config {
  static String? getAppName() {
    return "null safty";
  }
}

class WeatherService {
  static List<double> getTemperatures() {
    return [20, 25, 30, 40, 35];
  }
}

This code will certainly fail if getAppName() returns a null. So, in that case, we’ll pass a null to the Text widget used in the title of AppBar.
But there are more subtle cases to consider: getTemperatures() could also return null. In that case, the for-loop will fail. Or getTemperatures() could return a list as expected, but that list might contain null values, in which case we’ll call round() on null, and the app will fail.

With null safety, you can reason about your code with more confidence. No more pesky runtime null dereferencing errors in deployed apps. Instead, you get static errors as you code.

Null safety principles

Dart null safety support is based on the following three core design principles:

  • Non-nullable by default. Unless you explicitly tell Dart that a variable can be null, it will be considered non-nullable. We chose this as the default because we found that non-null was by far the most common choice in APIs.
  • Incrementally adoptable. There’s a lot of Dart code out there. It will be possible to migrate to null safety at a time when you choose to, and then incrementally, part by part. It will be possible to have null-safe and non-null-safe codes in the same project. We’ll also provide tools to help you with the migration.
  • Fully sound. Dart’s null safety is sound. This means that we can trust the type system: if it determines that something isn’t null, then it can never be null. This enables compiler optimizations. Once you migrate your whole project and your dependencies to null safety, you reap the full benefits of soundness — not only fewer bugs but smaller binaries and faster execution.

Output

Null Safety Flutter
Null Safety Flutter

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have seen what is a Null safety error in Flutter. Also, feel free to comment and provide any other suggestions regarding Flutter tips & tricks.

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. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

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


ready to get started?

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

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on