ViewChild is null because it is not in dom (NGIF), is there a way to write a function to run when it is found?


My design:

I have a Tab, which leverages NGIF, so the child content is not in the dom. The issue is that the inner component requires a subscription set up. Is there a way such that my ViewChild, when not null, can run a function?

MyCustomClass foo;

StreamSubscription sub = null;

To me, I was thinking that I would need to do some sort of while loop, with a delay to periodically check foo to see if it is not null.

setUp() async {
  while(sub == null){
    if (foo != null){
       sub = foo.onChanged.listen((_)=>_func());
    await new Future.delayed(new Duration(seconds: 1));

but it seems kinda dirty.

Is there a way to set up in your init file to do something akin to:

  // foo.when( () => foo !=null, (){ 
  //   sub = foo.onChanged.listen((_)=>_func());
  // });

Obviously that is in pseudocode, but i thought there might be a better option than some polling code in order to keep checking nullness.


Make foo a setter:

MyCustomClass _foo;

set foo(MyCustomClass value) {
  _foo = value;

Answered By – Günter Zöchbauer

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *