How do I check if a value is null in flutter?

How do we check if a value is null in Flutter? We need to do that because we want that our app shouldn’t give us any ugly error while running.

As flutter and dart progress together, to give users more faster and safer experience, sound null safety becomes mandatory.

In a couple of articles, we’ll try to understand what is sound null safety?

Since this article is a mere introduction, so we presume that a Flutter beginner should understand the concept first.

Let us start from a Dart console application. And after that, we’ll test sound null safety in a Flutter App.

To demonstrate the examples we have two different GitHub repositories, one for Dart console application, and the other for the Flutter sound null safety.

What is sound null safety in Dart?

Let us assume we have a class in our lib folder of the Dart console application.

class SoundNullSafety {
  /// public properties
  ///
  /// anyone can access them from outside
  var publicName;
  var publicNumber;

  /// private properties
  ///
  /// no one can access from outside
  var _privateName;
  var _privateNumber;

  var result;

  String get getName => _privateName;
  set getName(String name) => _privateName = name;

  int get getNumber => _privateNumber;
  set getNumber(int numberSet) => _privateNumber = numberSet;

  void addTwoNames(String? firstName, String? secondName) =>
      print('$firstName' ' ' '$secondName');
  void addTwoNumbers(int? firstNumber, int? secondNumber) =>
      print('Addition of two numbers $firstNumber and '
          ' $secondNumber: ${firstNumber! + secondNumber!}');

  void letUsAdd({int? first, int? second}) {
    print('Addition of two numbers $first and $second: ${first! + second!}');
  }
}

class Name {
  late String _name;
  String get getName => _name;
  set setName(String aValue) => _name = aValue;
}

The above code is self-explanatory. We have two classes. Both have some public and private properties. As a result, we have get and set methods so that we can access the private properties while we instantiate the classes.

To check the sound null safety, we have used “?” and “!” so that we can pass a null value. Watch this part of the above code specifically.

 void addTwoNames(String? firstName, String? secondName) =>
      print('$firstName' ' ' '$secondName');
  void addTwoNumbers(int? firstNumber, int? secondNumber) =>
      print('Addition of two numbers $firstNumber and '
          ' $secondNumber: ${firstNumber! + secondNumber!}');

  void letUsAdd({int? first, int? second}) {
    print('Addition of two numbers $first and $second: ${first! + second!}');
  }

Therefore in our bin folder we have defined the main method where we’ve instantiated the classes.

import 'package:dart_common_problems/sound_null_safety.dart';

void main(List<String> args) {
  var instanceOfGetterAndSetter = SoundNullSafety();
  instanceOfGetterAndSetter.publicName = 'John';
  instanceOfGetterAndSetter.getName = 'Smith';
  var firstName, secondName, secondNumber;
  firstName = instanceOfGetterAndSetter.publicName;
  secondName = instanceOfGetterAndSetter.getName;
  instanceOfGetterAndSetter.getNumber = 23;
  secondNumber = instanceOfGetterAndSetter.getNumber;

  instanceOfGetterAndSetter.addTwoNames(firstName, secondName);
  instanceOfGetterAndSetter.addTwoNames('Json', 'Web');
  instanceOfGetterAndSetter.addTwoNumbers(5, secondNumber);
  instanceOfGetterAndSetter.letUsAdd(first: 5, second: 10);

  var name = Name();
  name.setName = 'Sanjib';
  print(name.getName);
}

We’ve not passed any null value. So the output is quite expected.

John Smith
Json Web
Addition of two numbers 5 and  23: 28
Addition of two numbers 5 and 10: 15
Sanjib

Now, what happens if we pass a null value instead of an integer value?

Dart ensures that we should never appoint null to any of those values. If that happens, the program will refuse to compile.

Sound null safety in Dart
Sound null safety in Dart

However, in Flutter we can use non-nullable types in the same way.

How do I make flutter null safe?

Let us assume a very simple flutter app, where we’ll have both values. Null and non-nullable.

We can test that in this widget.

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class SoundNullSafety extends StatelessWidget {
  const SoundNullSafety({Key? key}) : super(key: key);

  final String aString = 'Beginning Flutter with Dart'; // Cannot be null.
  final String? aNullableString = null; // Can be null.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Nullable Fields Demo'),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.all(10.0),
              padding: const EdgeInsets.all(10.0),
              color: Colors.brown[100],
              child: Text(
                'A String is $aString.',
                style: const TextStyle(
                  fontSize: 40.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10.0),
              padding: const EdgeInsets.all(10.0),
              color: Colors.redAccent,
              child: Text(
                'A nullable String is $aNullableString.',
                style: const TextStyle(
                  fontSize: 40.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Will that refuse to compile? No. On the contrary, it treats both strings in a different way.

Why?

Because, we’ve already made Flutter aware that, we’re going to pass a NULL value to a string.

final String aString = 'Beginning Flutter with Dart'; // Cannot be null.
  final String? aNullableString = null; // Can be null.

As a result, if we run the app, we get this display, without any compilation error.

Sound null safety in Flutter
Sound null safety in Flutter

If we add a null value instead of a string to the string which cannot be null, it gives us red line and keeps telling us that we cannot supply a null value to a string which cannot be a null.

Passing Null value to a non-nullable string
Passing Null value to a non-nullable string

In fact, in Dart, we could have done the same thing. In the next tutorial, we’ll discuss that.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Photo by Tamara Bellis on Unsplash

Comments

3 responses to “How do I check if a value is null in flutter?”

  1. […] my previous article on sound null safety of Flutter and Dart, I simply forgot to discuss another keyword […]

  2. […] How do I check if a value is null in flutter and late in Dart and Flutter. […]

  3. […] How do I check if a value is null in flutter? […]

Leave a Reply