Home > database >  Flutter webview app closes when back button pressed
Flutter webview app closes when back button pressed

Time:11-09

I have a simple webview application, when i go some pages and press back button it closes the app. I want to go previous page when back button pressed. But my code give error on

Try correcting the name to the name of an existing method, or defining a method named '_onWillPop'.
        onWillPop: () => _onWillPop(context),
return Scaffold(
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            WillPopScope(
              onWillPop: () => onWillPop(context),
              child: WebView(
                javascriptMode: JavascriptMode.unrestricted,
                initialUrl: 'https://google.com',
               
                navigationDelegate: (NavigationRequest request) {
                  setState(() {
                    isLoading = true;
                  });
                  return NavigationDecision.navigate;
                },
                onPageFinished: (String url) {
                  setState(() {
                    isLoading = false;
                  });
                },

                // onPageFinished: (finish) {
                //   setState(() {
                //     var isLoading = false;
                //   });
                // },
              ),
            ),
            isLoading
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : Stack(),
          ],
        ),
      ),
    );

CodePudding user response:

you Need to create method for onWillPopScope

this is example

Future<bool> initBackButton() async {
    Logger().d('back button pressed');
    return await showDialog(
          context: context,
          builder: (context) => ElasticIn(
            child: AlertDialog(
              title: const Text('Exit App'),
              content: const Text('Do you really want to exit ?'),
              actions: [
                ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('No'),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('Yes'),
                ),
              ],
            ),
          ),
        ) ??
        false;
  }

after that call like this

onWillPop: () => initBackButton,
  • Related