skip to Main Content

After checking various pages and ChatGPT, I need to ask for help here. I want to have a logic that once I am logged into the app and navigate through the pages, the back button should always navigate back to the home page. I am not talking about the leading back button, that one is disabled. It is the behavior when the use is using the device back button.

On the home page I have disables the back button with:

return PopScope(
canPop: false

Now on the other pages like the profile, I want the back button to navigate to the home page. Do I need PopScope for it and if so how can I do it? I tried it, but failed hard on that 😀 The Flutter dev documentation didn’t help either. 🙁

3

Answers


  1. You could specify a custom leading widget for your AppBar if the user is logged in.

    In the example below, the leading widget is an IconButton with an onPressed callback that takes care of the navigation.

    import 'package:flutter/material.dart';
    import 'package:go_router/go_router.dart';
    
    class CustomPage extends StatelessWidget {
      const CustomPage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            leading: isLoggedIn ? IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () => GoRouter.of(context).go('/')) : null, // Navigate                  
             title: const Text('CustomPage'),                          //  to home            
          ),
          body: ... , 
          ), 
        );
      }
    }
    
    Login or Signup to reply.
  2. import 'package:flutter/material.dart';
    
    class CustomPage extends StatelessWidget {
      const CustomPage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () => Navigator.of(contex).push(
    MaterialPageRoute<void>(builder: (BuildContext _) => YourPage(),
    ),),              
             title: const Text('YourPage'),                            
          ),
          body: .......... , 
          ), 
        );
      }
    }
    

    Without using third party libraries. Try it with MaterialPageRoute

    Login or Signup to reply.
  3. vous pouvez essaiyer d executer la route dans la methode pour navigue vers la page d accueil dans le dispose() de la page , la si l utilisateur essai de quitte la page il sera rediriger vers la page d accueil.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search