Home > Mobile >  What is the ambiguate function doing?
What is the ambiguate function doing?

Time:12-18

This is a function in the main.dart file of the just_audio example. I don't understand what's going on with the "ambiguate" line. I understand the bang operator in this context casts to the "underlying type" but in this case there is no underlying type, I don't think. The underlying type is <T?>. I'm only familiar with what that means when I see it in documentation as "a type goes here." If it's in actual code, not sure what it's doing.

void initState() {
    super.initState();
    ambiguate(WidgetsBinding.instance)!.addObserver(this);
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.black,
    ));
    _init();
  }

The ambiguate function from common.dart in the same lib folder:

T? ambiguate<T>(T? value) => value;

https://github.com/ryanheise/just_audio/tree/minor/just_audio/example/lib

CodePudding user response:

The ambiguate function casts a value to its nullable type, so an int is cast to int?.

That allows using the ! (null assert) operator on the value without a warning, because a value of type int cannot be null, so you don't need to assert that it isn't.

The reason for doing so is that in a program which also contains non-null-safe code, the value can actually be null at runtime.

The only reason to use the function is that you expect your code to run against two different and incompatible versions of the same library, one non-null-safe where a function can return null, and a newer null-safe version where the function cannot return null and is typed as such. Then you can do ambiguate(uncertainValue)?.doSomething(), and it does something if the value isn't null, and it compiles against both versions without warning.

If you are not trying to make your code work against two different versions of the same library, which differ in nullability-behavior, then don't use ambiguate. Even then, consider whether it'd just be easier to require the new version of the library, and lean into null safety.

(This particular use seems unnecessary. Doing ambiguate(something)!.method() will throw an error if the value is null, but so will something.method(), which will also not give any warnings.)

  • Related