website icon indicating copy to clipboard operation
website copied to clipboard

In flutter web app, How to handle browser backward and forward arrow button click?

Open kaushikbh99 opened this issue 1 year ago • 4 comments

Page URL

https://docs.flutter.dev/cookbook/navigation/named-routes/

Page source

https://github.com/flutter/website/tree/main/src/content/cookbook/navigation/named-routes.md

Describe the problem

I can not get callback while clicking on browser backward and forward arrow button click.

Expected fix

No response

Additional context

No response

I would like to fix this problem.

  • [X] I will try and fix this problem on docs.flutter.dev.

kaushikbh99 avatar Aug 01 '24 04:08 kaushikbh99

@johnpryan, he says he will try to fix it, but in case you have any specific guidance...

sfshaza2 avatar Aug 01 '24 17:08 sfshaza2

Hi @kaushikbh99, can you describe more what developer scenario you are trying to document? Is there an API that you are using that we currently don't give enough visibility on?

johnpryan avatar Aug 08 '24 17:08 johnpryan

IMG_20240814_131918

I'm asking about this forward and backword buttons. How can handle this buttons clicking action? How can block this button clicks in flutter web app?

kaushikbh99 avatar Aug 14 '24 07:08 kaushikbh99

@johnpryan, @sfshaza2

Currently I have use this temporary solution This method I have to call in each page initState

  static void onWebPageBackWard(
      {void Function(PopStateEvent)? onBackAction,
      void Function()? onDone,
      bool? cancelOnError,
      Function? onError}) {
    if (kIsWeb) {
      window.onPopState.listen(onBackAction,
          onDone: onDone, cancelOnError: cancelOnError, onError: onError);
    }
  }

if you want to block backward action so you call navigate on same page in onBackAction method. I have show in example


  @override
  void initState() {
    _onWebPop();
    super.initState();
  }
  
  Future<void> _onWebPop() async {
    await Future.delayed(const Duration(seconds: 1));
    if (kIsWeb) {
      String url = window.location.href;
  
      print('AAA:: $url');
      
      AppUtil.onWebPageBackWard(
        onBackAction: (p0) async {
            await appRouter.navigate(HomeRoute());
          //window.location.href = url;
        },
      );
    }
  }
  
  

You can navigate on same page so both button's click block.

kaushikbh99 avatar Aug 14 '24 07:08 kaushikbh99