flutter_webview_plugin.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. /// TODO: iOS implementation
  12. final StreamController<String> _onUrlChanged =
  13. new StreamController.broadcast();
  14. static FlutterWebviewPlugin _instance;
  15. FlutterWebviewPlugin._() {
  16. _init();
  17. }
  18. factory FlutterWebviewPlugin() => _instance ??= new FlutterWebviewPlugin._();
  19. _init() {
  20. _channel.setMethodCallHandler(_handleMessages);
  21. }
  22. Future<Null> _handleMessages(MethodCall call) async {
  23. switch (call.method) {
  24. case "onDestroy":
  25. _onDestroy.add(null);
  26. break;
  27. case "onBackPressed":
  28. _onBackPressed.add(null);
  29. break;
  30. case "onUrlChanged":
  31. _onUrlChanged.add(call.arguments["url"]);
  32. break;
  33. }
  34. }
  35. //////////////////////
  36. /// Listening the OnDestroy LifeCycle Event for Android
  37. ///
  38. Stream<Null> get onDestroy => _onDestroy.stream;
  39. /// Listening the onBackPressed Event for Android
  40. ///
  41. Stream<Null> get onBackPressed => _onBackPressed.stream;
  42. /// Start the Webview with [url]
  43. /// - [withJavascript] enable Javascript or not for the Webview
  44. /// - [clearCache] clear the cache of the Webview
  45. /// - clearCookies] clear all cookies of the Webview
  46. Future<Null> launch(String url,
  47. {bool withJavascript: true,
  48. bool clearCache: false,
  49. bool clearCookies: false,
  50. bool fullScreen: true}) =>
  51. _channel.invokeMethod('launch', {
  52. "url": url,
  53. "withJavascript": withJavascript,
  54. "clearCache": clearCache,
  55. "clearCookies": clearCookies,
  56. "fullScreen": fullScreen
  57. });
  58. /// Close the Webview
  59. /// Will trigger the [onDestroy] event
  60. Future<Null> close() => _channel.invokeMethod("close");
  61. /// Listening url changed
  62. ///
  63. Stream<String> get onUrlChanged => _onUrlChanged.stream;
  64. }