Flutter使用url_launcher打开的内嵌网页无关闭按钮,如何解决?
问题描述

有时用户会被困在打开的页面里,因为顶部没有关闭按钮。能不能让这个按钮显示出来?还是我只能设置成在浏览器中打开链接?
我正在使用url_launcher包,代码如下:
MaterialButton( color: Colors.blue, child: Row( children: [ Text( 'تصويت', style: TextStyle( fontSize: 25, color: Colors.white, fontWeight: FontWeight.bold), ), Icon( Icons.poll, size: 35, color: Colors.white, ) ], ), onPressed: () async { String urlprivsy = '${data.docs[index]['poll']}'; if (await canLaunch(urlprivsy)) { await launch( urlprivsy, forceSafariVC: true, forceWebView: true, enableJavaScript: true, ); } }, ),
解决方案
方案1:改用系统浏览器打开(快速解决)
你当前强制用App内WebView打开页面,导致没有默认关闭按钮。改成让系统默认浏览器打开,就会自带关闭/返回功能,用户不会被困住。修改代码如下:
await launch( urlprivsy, forceSafariVC: false, forceWebView: false, enableJavaScript: true, );
方案2:自定义带关闭按钮的内嵌WebView(更优体验)
如果想保留App内打开的体验,url_launcher的WebView模式无法自定义导航栏,建议改用webview_flutter包实现:
- 先在
pubspec.yaml添加依赖:
dependencies: webview_flutter: ^4.4.0
- 替换原按钮点击逻辑,打开自定义WebView页面:
import 'package:webview_flutter/webview_flutter.dart'; // 按钮点击事件 onPressed: () { String urlprivsy = '${data.docs[index]['poll']}'; Navigator.push( context, MaterialPageRoute( builder: (context) => Scaffold( appBar: AppBar( leading: IconButton( icon: Icon(Icons.close), onPressed: () => Navigator.pop(context), // 关闭页面 ), ), body: WebView( initialUrl: urlprivsy, javascriptMode: JavascriptMode.unrestricted, ), ), ), ); },
内容的提问来源于stack exchange,提问作者ItsSaed
相关产品推荐
相关产品推荐

