In my app I use instagram implicit authentification, which implies to login user in webview and get token from redirect url.
(在我的应用程序中,我使用instagram隐式身份验证,这意味着要在Webview中登录用户并从重定向URL获取令牌。)
I use flutter_webview_plugin Next code builds WebviewScaffold with login url. (我使用flutter_webview_plugin接下来的代码使用登录URL构建WebviewScaffold。)
And it listen for url changes. (并监听网址更改。)
So when response is redirected to my redirectUrl it parses url to get token. (因此,当响应重定向到我的redirectUrl时,它将解析url以获取令牌。)
Then you need to save token for following requests in app. (然后,您需要为应用中的以下请求保存令牌。)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => new _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final flutterWebviewPlugin = new FlutterWebviewPlugin();
StreamSubscription _onDestroy;
StreamSubscription<String> _onUrlChanged;
StreamSubscription<WebViewStateChanged> _onStateChanged;
String token;
@override
void dispose() {
// Every listener should be canceled, the same should be done with this stream.
_onDestroy.cancel();
_onUrlChanged.cancel();
_onStateChanged.cancel();
flutterWebviewPlugin.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
flutterWebviewPlugin.close();
// Add a listener to on destroy WebView, so you can make came actions.
_onDestroy = flutterWebviewPlugin.onDestroy.listen((_) {
print("destroy");
});
_onStateChanged =
flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged state) {
print("onStateChanged: ${state.type} ${state.url}");
});
// Add a listener to on url changed
_onUrlChanged = flutterWebviewPlugin.onUrlChanged.listen((String url) {
if (mounted) {
setState(() {
print("URL changed: $url");
if (url.startsWith(Constants.redirectUri)) {
RegExp regExp = new RegExp("#access_token=(.*)");
this.token = regExp.firstMatch(url)?.group(1);
print("token $token");
saveToken(token);
Navigator.of(context).pushNamedAndRemoveUntil(
"/home", (Route<dynamic> route) => false);
flutterWebviewPlugin.close();
}
});
}
});
}
@override
Widget build(BuildContext context) {
String loginUrl = "someservise.com/auth";
return new WebviewScaffold(
url: loginUrl,
appBar: new AppBar(
title: new Text("Login to someservise..."),
));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…