main.dart 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
  4. const kAndroidUserAgent =
  5. 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36';
  6. String selectedUrl = 'https://flutter.io';
  7. // ignore: prefer_collection_literals
  8. final Set<JavascriptChannel> jsChannels = [
  9. JavascriptChannel(
  10. name: 'Print',
  11. onMessageReceived: (JavascriptMessage message) {
  12. print(message.message);
  13. }),
  14. ].toSet();
  15. void main() => runApp(MyApp());
  16. class MyApp extends StatelessWidget {
  17. final flutterWebViewPlugin = FlutterWebviewPlugin();
  18. @override
  19. Widget build(BuildContext context) {
  20. return MaterialApp(
  21. title: 'Flutter WebView Demo',
  22. theme: ThemeData(
  23. primarySwatch: Colors.blue,
  24. ),
  25. routes: {
  26. '/': (_) => const MyHomePage(title: 'Flutter WebView Demo'),
  27. '/widget': (_) {
  28. return WebviewScaffold(
  29. url: selectedUrl,
  30. javascriptChannels: jsChannels,
  31. mediaPlaybackRequiresUserGesture: false,
  32. appBar: AppBar(
  33. title: const Text('Widget WebView'),
  34. ),
  35. withZoom: true,
  36. withLocalStorage: true,
  37. hidden: true,
  38. initialChild: Container(
  39. color: Colors.redAccent,
  40. child: const Center(
  41. child: Text('Waiting.....'),
  42. ),
  43. ),
  44. bottomNavigationBar: BottomAppBar(
  45. child: Row(
  46. children: <Widget>[
  47. IconButton(
  48. icon: const Icon(Icons.arrow_back_ios),
  49. onPressed: () {
  50. flutterWebViewPlugin.goBack();
  51. },
  52. ),
  53. IconButton(
  54. icon: const Icon(Icons.arrow_forward_ios),
  55. onPressed: () {
  56. flutterWebViewPlugin.goForward();
  57. },
  58. ),
  59. IconButton(
  60. icon: const Icon(Icons.autorenew),
  61. onPressed: () {
  62. flutterWebViewPlugin.reload();
  63. },
  64. ),
  65. ],
  66. ),
  67. ),
  68. );
  69. },
  70. },
  71. );
  72. }
  73. }
  74. class MyHomePage extends StatefulWidget {
  75. const MyHomePage({Key key, this.title}) : super(key: key);
  76. final String title;
  77. @override
  78. _MyHomePageState createState() => _MyHomePageState();
  79. }
  80. class _MyHomePageState extends State<MyHomePage> {
  81. // Instance of WebView plugin
  82. final flutterWebViewPlugin = FlutterWebviewPlugin();
  83. // On destroy stream
  84. StreamSubscription _onDestroy;
  85. // On urlChanged stream
  86. StreamSubscription<String> _onUrlChanged;
  87. // On urlChanged stream
  88. StreamSubscription<WebViewStateChanged> _onStateChanged;
  89. StreamSubscription<WebViewHttpError> _onHttpError;
  90. StreamSubscription<double> _onProgressChanged;
  91. StreamSubscription<double> _onScrollYChanged;
  92. StreamSubscription<double> _onScrollXChanged;
  93. final _urlCtrl = TextEditingController(text: selectedUrl);
  94. final _codeCtrl = TextEditingController(text: 'window.navigator.userAgent');
  95. final _scaffoldKey = GlobalKey<ScaffoldState>();
  96. final _history = [];
  97. @override
  98. void initState() {
  99. super.initState();
  100. flutterWebViewPlugin.close();
  101. _urlCtrl.addListener(() {
  102. selectedUrl = _urlCtrl.text;
  103. });
  104. // Add a listener to on destroy WebView, so you can make came actions.
  105. _onDestroy = flutterWebViewPlugin.onDestroy.listen((_) {
  106. if (mounted) {
  107. // Actions like show a info toast.
  108. _scaffoldKey.currentState.showSnackBar(
  109. const SnackBar(content: const Text('Webview Destroyed')));
  110. }
  111. });
  112. // Add a listener to on url changed
  113. _onUrlChanged = flutterWebViewPlugin.onUrlChanged.listen((String url) {
  114. if (mounted) {
  115. setState(() {
  116. _history.add('onUrlChanged: $url');
  117. });
  118. }
  119. });
  120. _onProgressChanged =
  121. flutterWebViewPlugin.onProgressChanged.listen((double progress) {
  122. if (mounted) {
  123. setState(() {
  124. _history.add('onProgressChanged: $progress');
  125. });
  126. }
  127. });
  128. _onScrollYChanged =
  129. flutterWebViewPlugin.onScrollYChanged.listen((double y) {
  130. if (mounted) {
  131. setState(() {
  132. _history.add('Scroll in Y Direction: $y');
  133. });
  134. }
  135. });
  136. _onScrollXChanged =
  137. flutterWebViewPlugin.onScrollXChanged.listen((double x) {
  138. if (mounted) {
  139. setState(() {
  140. _history.add('Scroll in X Direction: $x');
  141. });
  142. }
  143. });
  144. _onStateChanged =
  145. flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state) {
  146. if (mounted) {
  147. setState(() {
  148. _history.add('onStateChanged: ${state.type} ${state.url}');
  149. });
  150. }
  151. });
  152. _onHttpError =
  153. flutterWebViewPlugin.onHttpError.listen((WebViewHttpError error) {
  154. if (mounted) {
  155. setState(() {
  156. _history.add('onHttpError: ${error.code} ${error.url}');
  157. });
  158. }
  159. });
  160. }
  161. @override
  162. void dispose() {
  163. // Every listener should be canceled, the same should be done with this stream.
  164. _onDestroy.cancel();
  165. _onUrlChanged.cancel();
  166. _onStateChanged.cancel();
  167. _onHttpError.cancel();
  168. _onProgressChanged.cancel();
  169. _onScrollXChanged.cancel();
  170. _onScrollYChanged.cancel();
  171. flutterWebViewPlugin.dispose();
  172. super.dispose();
  173. }
  174. @override
  175. Widget build(BuildContext context) {
  176. return Scaffold(
  177. key: _scaffoldKey,
  178. appBar: AppBar(
  179. title: const Text('Plugin example app'),
  180. ),
  181. body: SingleChildScrollView(
  182. child: Column(
  183. mainAxisAlignment: MainAxisAlignment.center,
  184. children: [
  185. Container(
  186. padding: const EdgeInsets.all(24.0),
  187. child: TextField(controller: _urlCtrl),
  188. ),
  189. RaisedButton(
  190. onPressed: () {
  191. flutterWebViewPlugin.launch(
  192. selectedUrl,
  193. rect: Rect.fromLTWH(
  194. 0.0, 0.0, MediaQuery.of(context).size.width, 300.0),
  195. userAgent: kAndroidUserAgent,
  196. invalidUrlRegex:
  197. r'^(https).+(twitter)', // prevent redirecting to twitter when user click on its icon in flutter website
  198. );
  199. },
  200. child: const Text('Open Webview (rect)'),
  201. ),
  202. RaisedButton(
  203. onPressed: () {
  204. flutterWebViewPlugin.launch(selectedUrl, hidden: true);
  205. },
  206. child: const Text('Open "hidden" Webview'),
  207. ),
  208. RaisedButton(
  209. onPressed: () {
  210. flutterWebViewPlugin.launch(selectedUrl);
  211. },
  212. child: const Text('Open Fullscreen Webview'),
  213. ),
  214. RaisedButton(
  215. onPressed: () {
  216. Navigator.of(context).pushNamed('/widget');
  217. },
  218. child: const Text('Open widget webview'),
  219. ),
  220. Container(
  221. padding: const EdgeInsets.all(24.0),
  222. child: TextField(controller: _codeCtrl),
  223. ),
  224. RaisedButton(
  225. onPressed: () {
  226. final future =
  227. flutterWebViewPlugin.evalJavascript(_codeCtrl.text);
  228. future.then((String result) {
  229. setState(() {
  230. _history.add('eval: $result');
  231. });
  232. });
  233. },
  234. child: const Text('Eval some javascript'),
  235. ),
  236. RaisedButton(
  237. onPressed: () {
  238. setState(() {
  239. _history.clear();
  240. });
  241. flutterWebViewPlugin.close();
  242. },
  243. child: const Text('Close'),
  244. ),
  245. RaisedButton(
  246. onPressed: () {
  247. flutterWebViewPlugin.getCookies().then((m) {
  248. setState(() {
  249. _history.add('cookies: $m');
  250. });
  251. });
  252. },
  253. child: const Text('Cookies'),
  254. ),
  255. Text(_history.join('\n'))
  256. ],
  257. ),
  258. ),
  259. );
  260. }
  261. }