在flutter中,当按下后退按钮时,我如何返回到上一个URL



我对flutter完全陌生,我正在使用web视图小部件,但每当我按下时,它就会退出应用程序。按下后退按钮时,如何返回上一页?

这是我的代码片段

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(MyApp());
WebViewController controllerGlobal;
Future<bool> _exitApp(BuildContext context) async {
if (await controllerGlobal.canGoBack()) {
print("onwill goback");
controllerGlobal.goBack();
return Future.value(true);
} else {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text("No back history item")),
);
return Future.value(false);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'TRAVMAKS',
home: WillPopScope(
onWillPop: () => _exitApp(context),
child:Scaffold(
body: Container(
margin: const EdgeInsets.only(top: 52.0),
child: Container(
margin: const EdgeInsets.only(top: 0.0),
child: WebView(
initialUrl: 'https://www.google.com',
javascriptMode: JavascriptMode.unrestricted,
)
)
)
)
)
);
}
}

在返回WebView后返回true。如果您在onWillPop中返回true,Flutter会弹出路由,如果这是您的根路由,应用程序将退出。你可能也想在那里返回false。

https://api.flutter.dev/flutter/widgets/WillPopScope/onWillPop.html

最新更新