flutter_webview_plugin.dart 1.8 KB

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