Search code examples
flutternavigator

how to know the current screen in Flutter?


I'm making a chat app and i want to send push notifications to an user only if he is not in the chat screen, so i need to know the current screen or path

I tried saving in state the name of the screen each time he enter to it, but of course it did´nt work when user go back with Navigator.pop or if he uses gestures

I don't know what is the right way to do it


Solution

  • Maybe you can use the dispose method to update the state whenever the user leaves the screen:

    import 'package:flutter/material.dart';
    
    class ChatScreen extends StatefulWidget {
      @override
      _ChatScreenState createState() => _ChatScreenState();
    }
    
    class _ChatScreenState extends State<ChatScreen> {
      bool userInChat = false;
    
      @override
      void initState() {
        super.initState();
        // Set the user as "in the chat" when the widget is initialized
      }
    
      @override
      void dispose() {
        // Set the user as "not in the chat" when the widget is disposed (he left the screen)
        super.dispose();
      }
    }
    

    The initState method is called when the widget is created, and the dispose method is called when the widget is removed from the widget tree, dispose is typically called when the user navigates away from the screen.