Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a widget/page is rendered?

Tags:

flutter

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

like image 482
Kostya Vyrodov Avatar asked Jan 22 '19 15:01

Kostya Vyrodov


2 Answers

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.

like image 95
Kostya Vyrodov Avatar answered Nov 08 '22 09:11

Kostya Vyrodov


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.

like image 36
GrahamD Avatar answered Nov 08 '22 08:11

GrahamD