webview_flutter使用步骤

470 阅读1分钟
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// 使用步骤分为3步
/// 1、初始化WebViewController
/// 2、重写这个WebViewController
/// 3、使用WebViewWidget实现外部页面嵌入

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  // 1
  late WebViewController controller;
  @override
  void initState() {
    // 2
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('https://www.jeyarlin.club/'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Simple Example')),
      body: Column(
        children: [
          // 3
          Expanded(child: WebViewWidget(controller: controller))
        ],
      ),
      floatingActionButton: ElevatedButton(
        onPressed: () async {
          var title = await controller.getTitle();
          // ignore: avoid_print
          print(title);
        },
        child: const Text('获取 title'),
      ),
    );
  }
}