flutter / website

Flutter documentation web site
https://docs.flutter.dev
Other
2.82k stars 3.22k forks source link

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

Open kaushikbh99 opened 3 months ago

kaushikbh99 commented 3 months ago

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.

sfshaza2 commented 3 months ago

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

johnpryan commented 2 months ago

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?

kaushikbh99 commented 2 months ago

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 commented 2 months ago

@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.