Search code examples
flutterdartnavigator

How do I check if the current widget is in the top-most context?


I have a widget which runs a function every minute when it's active. However, I don't want this function to run when I have pushed another page above the widget, so I wanted to wrap the function in a conditional which is only true when the current widget is in the top-most context (i.e., there are no pages which have been pushed above it).

I tried to find a way of doing this, but was unsuccessful, so any guidance or suggestions would be appreciated.

Thank you.


Solution

  • You can use the ModalRoute.of(context) to check if the current route is the top-most route in the navigator stack.

    import 'dart:async';
    
    import 'package:flutter/material.dart';
    
    class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      late Timer timer;
    
      @override
      void initState() {
        super.initState();
        timer = Timer.periodic(Duration(minutes: 1), (timer) {
          if (ModalRoute.of(context)?.isCurrent ?? false) {
            // Run your function here
            print('Some function executed here');
          }
        });
      }
    
      @override
      void dispose() {
        timer.cancel();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('My Widget'),
          ),
          body: Center(
            child: Text('My Widget Body'),
          ),
        );
      }
    }
    

    In the above example, we check if the route we are in is the current route by doing ModalRoute.of(context)?.isCurrent. When that is true, the periodic function will only run.