What is a Null safety in Flutter?

· 5 min read
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) {
    // Get data from services. Note: in a real application,
    // these would be async calls, but we're using sync calls
    // for simplicity.
    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: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Temperature next 3 days:'),
              for (final t in temperatures) 
                Text(t.round().toString()),
            ],
          ),
        ),
      ),
    );
  }
}
class Config {
  static String getAppName() { ... }
}
class WeatherService {
  static List<double> getTemperatures() { ...}
}

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.

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.

Leave a Reply