import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class BaseWebview extends StatefulWidget {
  final Map<String, dynamic> model;

  const BaseWebview(this.model, {Key key}) : super(key: key);

  @override
  _BaseWebviewState createState() => _BaseWebviewState();
}

class _BaseWebviewState extends State<BaseWebview> {
  String _url;
  String _title;
  WebViewController _webViewController;

  @override
  void initState() {
    _url = widget.model['url'] ?? '';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createNav(),
      backgroundColor: Colors.white,
      body: WebView(
        initialUrl: _url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _webViewController = webViewController;
        },
        navigationDelegate: (NavigationRequest request) {
          return NavigationDecision.navigate;
        },
        onPageStarted: (String url) {
          print('Page started loading: $url');
        },
        onPageFinished: (String url) {
          print('Page finished loading: $url');
          _webViewController.getTitle().then((title) {
            _title = title;
            setState(() {});
          });
        },
        gestureNavigationEnabled: true,
      ),
    );
  }

// 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: Colors.white,
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        _title ?? '',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xff333333),
        ),
      ),
      trailing: GestureDetector(
        child: Icon(
          Icons.refresh,
          size: 20,
        ),
        onTap: () {
          _webViewController.reload();
        },
      ),
    );
  }
}
