Search code examples
flutterdartdart-null-safety

Flutter conditional rendering with null-safety


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(),
          ),
      ],
    );
  }
}

Solution

  • 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(),
              ),
          ],
        );
      }
    }