1

I have problems with Dart null safety.

Even when I explicitly check for nulls, it still complainsenter image description here

The exclamation mark is solving that

enter image description here

but it's pretty ugly and cumbersome.

Is there a way to make it smarter and nicer? Like e.g. header?.let{ it.toUpperCase() } in Kotlin?

jakub
  • 3,576
  • 3
  • 29
  • 55
  • 1
    For a explanation for why it does not promote: https://stackoverflow.com/questions/65456958/dart-null-safety-doesnt-work-with-class-fields/65457221#65457221 – julemand101 Mar 18 '21 at 19:00
  • And https://stackoverflow.com/questions/65035574/null-check-doesnt-cause-type-promotion-in-dart. You can avoid it by using a local variable: `var header = this.header;`. – jamesdlin Mar 18 '21 at 22:42

1 Answers1

2

I suppose that header has a type of String?. It seems that variables used in logical expressions must be part of the local scope of the current context. In your example, passing down header as a String? typed argument allow your to access String methods if its value is not null.

  Widget _buildHeader(String? header) {
    if (header != null) {
      return Text(h.toUpperCase());
    }
    return Container();
  }

glavigno
  • 483
  • 5
  • 10