1.首先引入flutter_inappwebview依赖
flutter pub add flutter_inappwebview
2.直接上代码
class LoginView extends StatefulWidget {
final String currentRoute;
const LoginView({super.key, required this.currentRoute});
@override
State<LoginView> createState() => _LoginViewState();
}Ï
class _LoginViewState extends State<LoginView> {
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
mediaPlaybackRequiresUserGesture: false,
transparentBackground: true,
verticalScrollBarEnabled: true,
javaScriptEnabled: true,
useShouldInterceptAjaxRequest: true,
supportZoom: true,
// cacheEnabled: true,
javaScriptCanOpenWindowsAutomatically: true,
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
allowsInlineMediaPlayback: true,
));
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
CookieManager cookieManager = CookieManager.instance();
Uri webViewUrl = Uri.parse("https://www.baidu.com");
return Scaffold(
appBar: null,
body: SafeArea(
child: InAppWebView(
initialUrlRequest: URLRequest(
headers: {'Cookie': 'name=test;age=12'}, //初始化时候的cookie
url: webViewUrl),
initialOptions: options,
onLoadStop: (controller, url) async {
List<Cookie> cookies =
await cookieManager.getCookies(url: webViewUrl);
await cookieManager.setCookie(
url: webViewUrl,
name: 'name',
value: 'test',
domain: ".baidu.com",
path: "/");
await cookieManager.setCookie(
url: webViewUrl,
name: 'age',
value: '12',
domain: ".baidu.com",
path: "/");
},
onUpdateVisitedHistory: (controller, url, androidIsReload) async {
//这里监听是监听webview内部url的变化 , 如果url是指定的可以加逻辑进行处理
if (url.toString().contains('url') &&
!url.toString().contains('url')) {
List<Cookie> cookies =
await cookieManager.getCookies(url: webViewUrl);
String cookieString = cookies
.map((cookie) => '${cookie.name}=${cookie.value}')
.join(';');
debugPrint('cookieString: $cookieString');
PreferencesDB.prefs.setString('cookie', cookieString);
Navigator.pushNamed(context, widget.currentRoute);
}
},
)));
}
}