When you press the back button, you can go to the previous page in the webview. Additionally, we would like to add that when you double-press back, the app will close.
https://pub.dev/packages/double_back_to_close_app
I think I can use this, but I don’t know how to apply both functions at the same time.
This is the code I created.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
final uri = Uri.parse('https://google.com');
class HomeScreen extends StatelessWidget {
WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (String url){
print(url);
}
))
..loadRequest(uri);
HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return PopScope(
canPop: /* BOOL VALUE THAT CHECK IF ITS OK TO CLOSE APP OR NOT , YOU MAY PASS FALSE:)*/ false ,
onPopInvoked: (didPop) {
//FUNCTION THAT CALL WHEN EVER THE BACK CLICKED :)
controller?.goBack();
},
child: Scaffold(
floatingActionButton: Container(
height: 40.0,
width: 40.0,
child: FittedBox(
child: FloatingActionButton(
child: Icon(Icons.arrow_back),
onPressed: () => controller?.goBack(),
backgroundColor: Colors.grey.shade200,
),
),
),
body: SafeArea(
child : WebViewWidget(
controller: controller,
),
),
),
);
}
}
2
Answers
Use an if check for onPressed call. Check if there is any route available to go then call the
Controller?.goBack(): SystemNavigator.pop();
Using a ternary check will save space and it will be easy. However, you must implement manual logic to check the available routes.
I hope It works.
Define a
currentPress
variable above the build method like this:and use
PopScope
to handle the backpress