Search code examples
flutterdartflutterflownull-check

Flutterflow/Dart: How to Assign Optional Value To Non-Optional Variable?


in Flutterflow custom code (Dart) I want to assign an optional that I've verified isn't null to a non-nullable temporary variable, like this:

class MyClass extends StatefulWidget {
  MyClass({
    super.key,
    this.param1,
    this.param2,
  });

  List<dynamic>? param1;
  List<dynamic>? param2;


  ... later on, in class methods ...


  List<dynamic> tmpList = [];
    
  if (widget.param1 != null) {
    tmpList = widget.param1;
  } else if (widget.param2 != null) {
    tmpList = widget.param2;
  }

}

But getting the following error:

A value of type 'List?' can't be assigned to a variable of type 'List'

Is there some other way I need to verify it's not null before I can assign it?

Similar code seems to work on https://dartpad.dev :

void main() {
  List<dynamic> tmp = [{
    "id": "abc"
  }];
  
  List<dynamic>? param1 = null;
  List<dynamic>? param2 = [{
    "id": "def"
  }];
  
  if (param1 != null) {
    tmp = param1;
  }
  if (param2 != null) {
    tmp = param2;
  }
  
  print(tmp); // returns "[{id: def}]"
}

Solution

  • The difference is that in your second code sample all are local variables, for which the compiler can infer that param1 and param2 can't be null by the time you assign them to tmp.

    In the MyClass example param1 and param2 are fields on the object, which means they may get a different value between the time you check if they're null and the time you assign them to tmpList .

    This for example should work in the class method you mention:

    final localParam1 = widget.param1;
    final localParam2 = widget.param2;
    if (localParam1 != null) {
      tmpList = localParam1;
    } else if (localParam2 != null) {
      tmpList = localParam2;
    }