main.dart 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
  4. void main() {
  5. runApp(new MyApp());
  6. }
  7. class MyApp extends StatelessWidget {
  8. @override
  9. Widget build(BuildContext context) {
  10. return new MaterialApp(
  11. title: 'Flutter WebView Demo',
  12. theme: new ThemeData(
  13. primarySwatch: Colors.blue,
  14. ),
  15. home: new MyHomePage(title: 'Flutter WebView Demo'),
  16. );
  17. }
  18. }
  19. class MyHomePage extends StatefulWidget {
  20. MyHomePage({Key key, this.title}) : super(key: key);
  21. final String title;
  22. @override
  23. _MyHomePageState createState() => new _MyHomePageState();
  24. }
  25. class _MyHomePageState extends State<MyHomePage> {
  26. // Instance of WebView plugin
  27. final FlutterWebviewPlugin flutterWebviewPlugin = new FlutterWebviewPlugin();
  28. // On destroy stream
  29. StreamSubscription _onDestroy;
  30. TextEditingController _ctrl = new TextEditingController(text: "https://flutter.io");
  31. GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();
  32. @override
  33. initState() {
  34. super.initState();
  35. // Add a listener to on destroy WebView, so you can make came actions.
  36. _onDestroy = flutterWebviewPlugin.onDestroy.listen((_) {
  37. if (mounted) {
  38. // Actions like show a info toast.
  39. _scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text("Webview Destroyed")));
  40. }
  41. });
  42. }
  43. @override
  44. void dispose() {
  45. // Every listener should be canceled, the same should be done with this stream.
  46. _onDestroy?.cancel();
  47. super.dispose();
  48. }
  49. @override
  50. Widget build(BuildContext context) {
  51. return new Scaffold(
  52. key: _scaffoldKey,
  53. appBar: new AppBar(
  54. title: new Text('Plugin example app'),
  55. ),
  56. body: new Column(
  57. mainAxisAlignment: MainAxisAlignment.center,
  58. children: [
  59. new Container(
  60. padding: const EdgeInsets.all(24.0),
  61. child: new TextField(controller: _ctrl),
  62. ),
  63. new RaisedButton(
  64. onPressed: _onPressed,
  65. child: new Text("Open Webview"),
  66. )
  67. ],
  68. ),
  69. );
  70. }
  71. void _onPressed() {
  72. try {
  73. // This way you launch WebView with an url as a parameter.
  74. flutterWebviewPlugin.launch(_ctrl.text);
  75. } catch (e) {
  76. print(e);
  77. }
  78. }
  79. }