If you want to login through a webview in flutter app? I use flutter_webview_plugin Next code builds WebviewScaffold with login url. And it listen for url changes. So when response is redirected to my redirectUrl it parses url to get token. Then you need to save token for following requests in app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 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..."), )); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.