flutter_webview_plugin.dart 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import 'dart:async';
  2. import 'package:flutter/services.dart';
  3. const _kChannel = 'flutter_webview_plugin';
  4. /// Singleton Class that communicate with a fullscreen Webview Instance
  5. /// Have to be instanciate after `runApp` called.
  6. class FlutterWebviewPlugin {
  7. final MethodChannel _channel = const MethodChannel(_kChannel);
  8. final StreamController<Null> _onDestroy = new StreamController.broadcast();
  9. final StreamController<Null> _onBackPressed =
  10. new StreamController.broadcast();
  11. final StreamController<String> _onUrlChanged =
  12. new StreamController.broadcast();
  13. static FlutterWebviewPlugin _instance;
  14. FlutterWebviewPlugin._() {
  15. _init();
  16. }
  17. factory FlutterWebviewPlugin() => _instance ??= new FlutterWebviewPlugin._();
  18. _init() {
  19. _channel.setMethodCallHandler(_handleMessages);
  20. }
  21. Future<Null> _handleMessages(MethodCall call) async {
  22. switch (call.method) {
  23. case "onDestroy":
  24. _onDestroy.add(null);
  25. break;
  26. case "onBackPressed":
  27. _onBackPressed.add(null);
  28. break;
  29. case "onUrlChanged":
  30. _onUrlChanged.add(call.arguments["url"]);
  31. break;
  32. }
  33. }
  34. //////////////////////
  35. /// Listening the OnDestroy LifeCycle Event for Android
  36. ///
  37. Stream<Null> get onDestroy => _onDestroy.stream;
  38. /// Listening the onBackPressed Event for Android
  39. ///
  40. Stream<Null> get onBackPressed => _onBackPressed.stream;
  41. /// Start the Webview with [url]
  42. /// - [withJavascript] enable Javascript or not for the Webview
  43. /// - [clearCache] clear the cache of the Webview
  44. /// - clearCookies] clear all cookies of the Webview
  45. Future<Null> launch(String url,
  46. {bool withJavascript: true,
  47. bool clearCache: false,
  48. bool clearCookies: false,
  49. bool fullScreen: true}) =>
  50. _channel.invokeMethod('launch', {
  51. "url": url,
  52. "withJavascript": withJavascript,
  53. "clearCache": clearCache,
  54. "clearCookies": clearCookies,
  55. "fullScreen": fullScreen
  56. });
  57. /// Close the Webview
  58. /// Will trigger the [onDestroy] event
  59. Future<Null> close() => _channel.invokeMethod("close");
  60. /// Listening url changed
  61. ///
  62. Stream<String> get onUrlChanged => _onUrlChanged.stream;
  63. }