Kostya Vyrodov
Kostya Vyrodov

Reputation: 7227

How to check if a widget/page is rendered?

Is there anything like componentWillDisapear() in RN?

Details of my issue:

I have two screens: Home and Details. My application uses 'firebase_admob' for adverts and the 'firebase_admob' (see the screenshot below) can render only fixed banner for the whole application. So when you go to other screens you see it too, but I need it only at Home screen. It means, when user navigates to Details I have to hide it. How to do it?

Note: I want to call dispose() when a user leaves the Home screen. To render the banner you need to call show() in BannerAd class and when you need to hide you just call dispose.

enter image description here

Upvotes: 16

Views: 27728

Answers (2)

Kostya Vyrodov
Kostya Vyrodov

Reputation: 7227

The code bellow allows to check if the page is visible for a user:

import 'package:flutter/material.dart';

class TestWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('TestWidget: ${ModalRoute.of(context).isCurrent}');
    return Container();
  }
}

And this sample allows to check when a route is changed. But you can't get current page name.

Upvotes: 45

GrahamD
GrahamD

Reputation: 3165

As an addition to Kostya Vyrodov's answer and in response to his comment 'But you can't get current page name.', the following code snippet will print the current page name.

print("context.widget.toStringShort: ${context.widget.toStringShort()}");

Typically, this is best used in the page's initState to save the page name to a global variable for use elsewhere in the app. For example, I use it with Firebase Cloud Messaging in the _firebaseMessaging.configure() method to determine specific navigation requirements. If someone finds this useful, please up-vote.

Upvotes: 7

Related Questions