1

I want to render Text widget if expires not null. So I did the check for null

But got the error

enter image description here

class TileButton extends StatelessWidget {
  final DateTime? expires;

  const TileButton({
    Key? key,
    this.expires,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(
          'Hello Flutter',
        ),
        if (expires != null)
          Text(
            expires.day.toString(),
          ),
      ],
    );
  }
}
teacake
  • 390
  • 4
  • 15

2 Answers2

7

thanks to the guy from the community. He show where I should look

So this check does not work with class fields

The analyzer can’t model the flow of your whole application, so it can’t predict the values of global variables or class fields.

For a non-local variable, the compiler cannot easily make that guarantee. Non-local variables implicitly provide getter functions, which could be overridden by derived class and which could return different values from one access to the next.

Also check link from comments from this posts for more info

Dart 2.1.0 smart cast using 'is' not working

Null check doesn't cause type promotion in Dart

Dart null safety doesn't work with class fields

So. If I want to use null check without using ! I should create local var final _expires = expires; and use _expires for check

class TileButton extends StatelessWidget {
  final DateTime? expires;

  const TileButton({
    Key? key,
    this.expires,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _expires = expires;
    return Row(
      children: [
        Text(
          'Hello Flutter',
        ),
        if (_expires != null)
          Text(
            _expires.day.toString(),
          ),
      ],
    );
  }
}
teacake
  • 390
  • 4
  • 15
0

You are using Flutter with null-safety enabled. (If this concept is new to you, read about it here Null safety in Flutter.)

The error seems to be complaining that in the expression expires.day.toString() the term expires can be null, which is not permitted with null-safety. You know that expires is not null, so you can assert that to prevent the error using ! as in expires!.day.toString().

Note that in simple Dart code, the compiler detects the test for non-null, and does not report an error, for example:

DateTime? test;
print('${test.day}');
if (test != null) {
  print('${test.day}');
}
var list = [
  test.day,
  if (test != null) test.day,
];

Here the first and third print statements have an error, the second and fourth do not. I do not know why this does not carry through into the Text widget.

Patrick O'Hara
  • 1,999
  • 1
  • 14
  • 18
  • If you interesting, check my answer below for posts which describes why I got the error even if I check for null – teacake Mar 27 '21 at 18:14